How can I include partial html in github's electron framework?

I suppose your question has been answered satisfactorily. But seeing how this question has quite a few views, I figured I'd give the folks a little more info on this:

Partials (snippets, components, whatever) of markup can be loaded in Electron from both angles; client-side and server-side.

Client-Side

For when you need to dynamically fetch content based on user actions (e.g. on button press).

This works the same in Electron as in any browser (except, of course, you have access to the file: protocol). You use ajax. Or any library containing a loading api (a friendly wrapper around ajax). So jQuery, angular, mithril, etc will all work.

Example:

$('#dynamic-content').load('file:///my-partial.html')

Server-Side

For when you want to serve (not lazy-load, e.g. with angular) modular HTML, with reusable components separated into their own files.

Modular markup is a must for large applications. To do this, you'll be using a templating engine of some sort. EJS is a very popular and good choice for this.

For server-side templating you have two options:

1) Pre-render

This may not be an option, depending on your use case. But if you know all variables beforehand, you can simply compile and render each entry file and save the results as html files.

Example using ejs and the node fs module:

let template = fs.readFileSync('my-page.ejs')
let compiled = ejs.render(tpl)
fs.writeFileSync('my-page.html', compiled)

And then load the html file normally, e.g.:

myBrowserWindow.loadURL('file:///my-page.html')

2) Intercept the file: protocol.

This is the real deal. Electron ships with a protocol module designed just for this. Here's a pseudo-code example with ejs:

Intercept all file requests.
If the file is not a `.ejs` file, serve the file.
If the file is a `.ejs` file, render it and serve the result.

And then you can load ejs to your heart's content:

myBrowserWindow.loadURL('file:///my-page.ejs')

I won't include a full code sample of protocol interception here, as you probably won't be implementing this yourself. Instead, I'd recommend using one of the many npm modules that do this for you:

  • electron-jade
  • electron-pug
  • ejs-electron (Disclosure: I am the author of this module).

If you want to take a swing at implementing this yourself, take a look at the Electron documentation of the protocol module. Cheers!


There are many ways to do that. At all you didn't give any information about when you want to load the dynamic content. I guess that it is a click on a link.

The solution is not different, when you would do that with a normal webpage.

Just to give you a hint:

  • Loading an HTML file into a DIV with a link
  • How do I load an HTML page in a <div> using JavaScript?
  • You can also solve it with jQuery http://api.jquery.com/load/
  • Or angular also gives you a possibility to do that.

Tags:

Electron