How to render multiple .ejs files in nested form in Node.js and Express?

后端 未结 2 948
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 05:16

How can I render multiple .ejs files in a nested form?

So I have the following file:

var mysql = require(\'mysql\');
var ejs = require(\         


        
相关标签:
2条回答
  • 2020-12-16 05:28

    First, I think you are confused on how res.render operates. According to the docs:

    res.render(view, [locals], callback)

    Render a view with a callback responding with the rendered string.

    which explains why you are only seeing the content of index2.ejs in your HTML page.


    Now, there are multiple ways to achieve your goal, which is nesting views within views. Starting from Express 3.x, you need to use include.In this case, you can rewrite your views like this:
    1- Define a header.ejs file, which would look like this example.
    2- Define a footer.ejs. which would look like this other example.
    3- In your index2.ejs, include these two files, like this:

    <% include header %>
        //The HTML of your index2.ejs
        //You can add some reusable views, like, say, a submit button above the footer
        <% include reusable_views/submit %>
    <% include footer %>
    

    A second method is to use ejs-locals, which allows you to insert any view by only specifying their path:

    res.render('index', {
                     title: 'title', 
                     content: 'index2', 
                     data:rows
                });
    

    And, in your index1.ejs, you will have:

    <html><head>
    <title><%= title %></title></head>
    <body><p>
    <%- partial('index2',{}) %>
    </p></body></html>
    

    The advantage of this method is you can pass extra values to your view, using the extra object. Check out the ejs-locals github page for more details.

    0 讨论(0)
  • 2020-12-16 05:39

    Update : ejs-mate Express 4.x locals for layout, partial.

    https://www.npmjs.com/package/ejs-mate

    cf https://scotch.io/tutorials/use-ejs-to-template-your-node-application

    0 讨论(0)
提交回复
热议问题