【问题标题】:Node Express EJS Dynamic template renderNode Express EJS 动态模板渲染
【发布时间】:2015-07-17 04:46:13
【问题描述】:

您好,我正在尝试在 express 中创建动态模板系统,我将从数据库中获取动态内容,然后在单个 index.ejs 文件中呈现输出。

这是我的 index.js

router.get('/', function(req, res, next) {

var dataFrmDB = {
       pageContent: "<%= data.pageTitle %>",
       pageTitle: "home"
   };

res.render('index', {data:dataFrmDB} );
});

并且 index.ejs 包含:

<%= data.pageContent %>

我应该怎么做才能将“家”渲染为输出。这可能吗?

【问题讨论】:

    标签: node.js express pug ejs


    【解决方案1】:

    当我们从drupal迁移到nodejs时,我正在做类似的事情,我使用ect而不是jade来渲染,它更快更容易处理,但是,如果你有一个更好的设计模式大动态网站

    js 控制器文件

    model.homepage(function(data)
    {
        res.render("homepage.ect",data,function(err,html)
                {
                   // Do something before you send the response such as minification, or error handling
                    res.send(html);
                });         
    });
    

    ECT 文件

    <html xmlns="http://www.w3.org/1999/xhtml" lang="ar" xml:lang="ar">
    <head>
         <%- @page.title.body %>
         <%- @page.headerScript.body %>
         <style type="text/css">#homepage-container{min-height:300px;color:#353535;float:right;width:100%}</style>
    </head>
    <body>
        <% include 'upper_bar.ect' %>
        <%- @page.headerAd.ads %>
        <%- @page.notifications.body %>
        <%- @page.autocomplete.body %>
        <%- @page.redirect.body %>
        <%- @page.navigation.body %>
        <%- @page.overlayAd.ads %>
    </body>
    </html>
    

    【讨论】:

    • 嗨@Abdullah,谢谢.. 即使我先渲染然后发送,它仍然在页面上显示模板代码作为字符串。
    • 您好,如果您使用的是 ect,您可以将 json 对象发送到视图,也就是说 var dataFrmDB = { pageContent: "this is what was come from DB", pageTitle: "home " };然后 res.render('index', {data:dataFrmDB} ) 并在视图中您可以执行
    • 我不认为它会这样做,因为它的方法与我已经在做的相同。除了使用 ETC。
    • 我们建立了一个像drupal一样大的网络平台,每月可以接收600万独立用户,如果这对您没有帮助,我希望您尽快找到解决方案:)
    • 我很欣赏你所做的,但你的答案根本不正确。
    【解决方案2】:

    为什么要这么麻烦?

    您可以使用templatesjs 轻松完成此操作 没有任何模板引擎。

    让我向您展示如何使用 templatesjs 完成您的工作 html 文件

    <html>
    <head>
        <title> <%title%> </title>
    </head>
    <body>
        your content goes here
    </body>
    </html>
    

    现在在你的 node.js 文件中使用 templatesjs

    var tjs = require("templatsjs");
    
    router.get('/', function(req, res, next) {
        var data = fs.readFileSync("./index.html");
        tjs.set(data); // invoke templatesjs 
        var output = tjs.render("title","home"); 
    
        /* this will replace the <%title%> tag 
           in the html page with actual title*/
        res.write(output);
        res.end()
    });
    

    我使用 fs.readFileSync 来保持代码的简单性,如果需要,您可以使用异步函数 (fs.readFile)。

    一个很好的参考可以找到here

    安装: $ npm install templatesjs

    【讨论】:

      猜你喜欢
      • 2012-05-08
      • 1970-01-01
      • 2021-04-27
      • 2023-03-19
      • 1970-01-01
      • 2016-02-26
      • 2014-11-24
      • 2016-11-01
      • 2012-11-27
      相关资源
      最近更新 更多