如何在电子框架中使用 html 模板? [英] How to use html templates in electron framework?

查看:16
本文介绍了如何在电子框架中使用 html 模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建一个具有多个窗口的跨平台应用程序.所以我想知道如何在电子中使用html模板.

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

推荐答案

基于一个类似的问题 和我所看到的,Electron 中没有内置的 html 模板语言,这实际上很棒,因为它允许您使用任何其他模板语言.

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.

我目前正在使用 Electron 中的 ejs.下面是我的 index.ejs 模板文件:

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

<html lang="en">
<head>
  <title>The Index Page</title>
</head>
<body>
  <h1>Welcome, this is the Index page.</h1>
  <% if (user) { %>
    <h3>Hello there <%= user.name %></h3>
  <% } %>
</body>
</html>

下面是我的 main.js 文件的一部分,上面的模板被渲染并加载到 BrowserWindow 上.请注意,我省略了大部分样板代码:

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));
});

我要感谢 这个 gist 帮助我找到 data:text/html;charset=utf-8 可用于加载动态内容的部分url.

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.

更新

我实际上不再使用它了.只加载默认 html 并使用本机 DOM 方法会更快.Electron Quickstart 程序展示了如何很好地做到这一点.

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.

这篇关于如何在电子框架中使用 html 模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆