如何在github的电子框架中包含部分html?

tt9*_*tt9 5 electron

在github的电子中,是否有一个包含部分html文件的内置机制?

例如,如果我在html中设计一个布局

<body>
    <div>
        <ul><li>Menu Item 1</li><li>Menu Item 2</li></ul>
    </div>
    <div id="dynamic-content">
        <!-- I would like this content to be loaded from partial html files -->
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

如何将来自不同文件的内容放入id为"dynamic-content"的div中?

bow*_*art 5

我想你的问题已经得到了满意的回答。但是看到这个问题有很多观点,我想我会给人们更多关于这个的信息:

标记的部分(片段、组件等)可以从两个角度加载到 Electron 中;客户端和服务器端。

客户端

当您需要根据用户操作(例如按下按钮)动态获取内容时。

这在 Electron 中与在任何浏览器中的工作方式相同(当然,您可以访问该file:协议)。你用阿贾克斯。或者任何包含加载 api(围绕 ajax 的友好包装器)的库。所以 jQuery、angular、mithril 等都可以使用。

例子:

$('#dynamic-content').load('file:///my-partial.html')
Run Code Online (Sandbox Code Playgroud)

服务器端

当您想要提供(不是延迟加载,例如使用 angular)模块化 HTML 时,将可重用组件分离到它们自己的文件中。

模块化标记是大型应用程序的必需品。为此,您将使用某种模板引擎。EJS 是一个非常受欢迎和不错的选择。

对于服务器端模板,您有两个选择:

1) 预渲染

这可能不是一种选择,具体取决于您的用例。但是如果你事先知道所有的变量,你可以简单地编译和渲染每个入口文件,并将结果保存为 html 文件。

使用 ejs 和 nodefs模块的示例:

let template = fs.readFileSync('my-page.ejs')
let compiled = ejs.render(tpl)
fs.writeFileSync('my-page.html', compiled)
Run Code Online (Sandbox Code Playgroud)

然后正常加载html文件,例如:

myBrowserWindow.loadURL('file:///my-page.html')
Run Code Online (Sandbox Code Playgroud)

2) 拦截file:协议。

这是实打实的。Electron 附带了一个protocol专门为此设计的模块。这是一个带有 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.
Run Code Online (Sandbox Code Playgroud)

然后你可以将 ejs 加载到你的心脏内容中:

myBrowserWindow.loadURL('file:///my-page.ejs')
Run Code Online (Sandbox Code Playgroud)

我不会在这里包含协议拦截的完整代码示例,因为您可能不会自己实现它。相反,我建议使用为您执行此操作的众多 npm 模块之一:

如果您想自己实现这一点,请查看协议模块的 Electron 文档。干杯!


apx*_*pxp 4

有很多方法可以做到这一点。您根本没有提供有关何时加载动态内容的任何信息。我猜这是点击链接。

当您使用普通网页执行此操作时,解决方案没有什么不同。

只是给你一个提示: