简体   繁体   中英

Templating in Electron?

Simple question here, but I found no useful resource. Is templating possible in Electron? Using Jade or Handlebars to display dynamic templates? I know there is.loadURL() that takes a static html file.

Is dynamic possible?

Thanks.

You could give electron-pug a chance. https://github.com/yan-foto/electron-pug

It would certainly be possible to use Jade or Handlebars for dynamic templating by running a local server in the Electron main process. I would not recommend this however, as it is kind of backwards. Electron is primarily a front end framework and while running a local server is good for some things, templating is not really one of them.

Most people use a frontend JS framework like Angular or React.

You can register a new buffer protocol via protocol.registerBufferProtocol .

main.js

var electron = require('electron');
var app = electron.app;
var protocol = electron.protocol;
var BrowserWindow = electron.BrowserWindow;
var pug = require('pug');

var window;

app.on('ready', function () {

  // Define the `pug` scheme
  protocol.registerBufferProtocol('pug', function (request, callback) {
    var url = path.normalize(request.url.substr(7));
    var content = pug.renderFile(url);
    callback({
      mimeType: 'text/html',
      data: new Buffer(content)
    });
  });

  window = new BrowserWindow({width: 600, height: 600});

  // Load your file using the `pug` protocol
  window.loadURL(url.format({
    pathname: path.join(__dirname, 'index.pug'),
    protocol: 'pug:',
    slashes: true
  }));

});

index.pug

html
  head
    title My title
  body
    h1 Hello world!

Probably too late to add here but thought it might be worthwhile. I have added a package to deal with adding views from any renderer and handle asset paths. So far I have just added the ejs renderer but plan on adding pug and haml as additional default renderers, but it is easy to extend and add your own as well. The package is called electron-view-renderer https://www.npmjs.com/package/electron-view-renderer

Hopefully this can help someone like it did our team. It is in its infancy, so all comments and contributions welcome

U can use ejs-electron to achieve the same purpose. U can check it out on github & simply install it as follows: npm i ejs-electron --save Just require it in ur main js file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM