【问题标题】:How to use html templates in electron framework?如何在电子框架中使用 html 模板?
【发布时间】:2017-03-09 20:47:44
【问题描述】:

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

【问题讨论】:

  • 电子应用程序界面运行 HTML、CSS 和 JavaScript。您只需要拥有 index.html、main.js 和 package.json 文件即可创建电子应用程序。见 - electron.atom.io/docs

标签: electron


【解决方案1】:

基于a similar question 和我所见,Electron 中没有内置的 html 模板语言,这实际上很棒,因为它允许您使用任何其他模板语言。

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

<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 上。请注意,我省略了大部分样板代码:

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

感谢 this gist 帮助我找到可用于加载动态内容的 URL 的 data:text/html;charset=utf-8 部分。

更新

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

【讨论】:

  • 我已尝试按照您的说法渲染 html,但现在无法使用我的 css 文件!你能帮帮我吗?
【解决方案2】:

另一种选择是在构建过程中进行模板化。这是一个使用 gulp 将 nonce 添加到 CSP 元标记和内联脚本的简单示例。

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'nonce-<%= scriptNonce %>';">
    <title>Basic Electron App</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="application/javascript" nonce=<%= scriptNonce %>>
      require('./index.js');
    </script>
  </body>
</html>

并在 gulfile.js 中将以下内容添加到您已有的内容中,并确保此任务包含在您的管道中。您也可以使用以下代码更新当前的 html 任务。

const template = require('gulp-template');
const uuidv4 = require('uuid/v4');

gulp.task('copy-html', () => {
  // Create nonces during the build and pass them to the template for use with inline scripts and styles
  const nonceData = {
    scriptNonce: new Buffer(uuidv4()).toString('base64'),
    styleNonce: new Buffer(uuidv4()).toString('base64')
  };
  return gulp.src('src/*.html')
  .pipe(template(nonceData))
  .pipe(gulp.dest('dist/'));
});

这是一个非常精简的示例。如果有人感兴趣,我在https://github.com/NFabrizio/data-entry-electron-app 有一个更完整的示例,尽管在运行应用程序时仍然有一个警告,因为我正在使用的包之一拉入 react-beautiful-dnd,它添加了内联样式但目前不接受随机数。

【讨论】:

  • 这会导致nonce的无限重复使用。
  • 这可能是真的,但我在这里的目的是演示如何在电子应用程序的构建阶段使用模板。
猜你喜欢
  • 2014-08-19
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 2020-02-17
  • 2016-04-06
相关资源
最近更新 更多