How to use html templates in electron framework?

后端 未结 2 1394
时光取名叫无心
时光取名叫无心 2021-01-14 06:03

I need to build a cross platform app with multiple windows. So I would like to know how to use html templates in electron.

2条回答
  •  孤城傲影
    2021-01-14 06:22

    Based on a similar question and what I've seen, there's no built in html template language in Electron, which is actually great because it allows you to use any other template language.

    I'm currently playing with ejs in Electron. Below is my index.ejs template file:

    
    
      The Index Page
    
    
      

    Welcome, this is the Index page.

    <% if (user) { %>

    Hello there <%= user.name %>

    <% } %>

    And below is a section of my main.js file where the above template is rendered and loaded onto the BrowserWindow. Note that I've left out most of the boilerplate code:

    const ejs = require('ejs');
    //... Other code
    let win = new BrowserWindow({width: 800, height: 600});
    //... Other code
    // send the data and options to the ejs template
    let data = {user: {name: "Jeff"}};
    let options = {root: __dirname};
    ejs.renderFile('index.ejs', data, options, function (err, str) {
      if (err) {
        console.log(err);
      }
      // Load the rendered HTML to the BrowserWindow.
      win.loadURL('data:text/html;charset=utf-8,' + encodeURI(str));
    });
    

    I'll give some credit to this gist for helping me find the data:text/html;charset=utf-8 part of the url that can be used to load dynamic content.

    UPDATE

    I'm actually not using this anymore. It's faster to just load the default html and use the native DOM methods. The Electron Quickstart program shows how to do this nicely.

提交回复
热议问题