【问题标题】:separate Handlebars HTML into multiple files / sections将 Handlebars HTML 分成多个文件/部分
【发布时间】:2018-12-03 08:31:03
【问题描述】:

我想创建一个只有一个路由的页面,但我想将 HTML 代码拆分为多个文件。

在渲染这条路线时,我希望渲染的文件从所有模板文件中获取内容并将其合并到一个页面中。

例如,此模板应呈现以下文件:

  • 标题
  • 简介
  • 服务
  • 关于
  • 联系方式
  • 版本说明

我只想将代码分开,因为这样我就可以建立一个干净的结构。那可能吗?目前我只能渲染一个文件

router.get('/', (req, res) => {
    res.render('myTemplate');
});

如果有默认 HTML 逻辑的方法,我不需要使用 Handlebars,因为我的页面只有一个模板。

【问题讨论】:

    标签: html node.js express handlebars.js


    【解决方案1】:

    假设您希望渲染一个文件,该文件是您的主文件并在其中包含页眉和页脚文件。让我们将您的主文件 main.hbs 以及页眉和页脚 html 文件称为 header.html 和 footer.html

    您的路线代码如下所示:

        router.get('/', (req, res) => {
        res.render('main');
    });
    

    header.html

    <h1> Hi I'm the Header </h1>
    

    页脚.html

    <h1> Hi I'm the Footer </h1>
    

    您可以使用 jQuery 在 main 中包含页眉和页脚模板

    main.hbs

    <html>
    <head>
    <title></title>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script> 
    $(function(){
      $("#header").load("header.html"); 
      $("#footer").load("footer.html"); 
    });
    </script> 
    </head>
    <body>
    <div id="header"></div>
    <!--Remaining section-->
    <div id="footer"></div>
    </body>
    </html>
    

    同样,您可以通过指定它们的 id 在主文件中包含 Intro、Service、About、Contact、Imprint 文件。

    【讨论】:

    • 所以不能做这个服务器端吗?因为我收到此错误Failed to load file:///C:/.../header.html: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
    • Chrome 使用 file: 协议阻止请求。你试过在 Firefox 上运行它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2013-09-10
    相关资源
    最近更新 更多