EJS - pass variable when include

☆樱花仙子☆ 提交于 2019-12-10 02:22:28

问题


I'm using ejs in backend with nodejs. I'd like to pass variable when include. When include the header, pass the page title.

index.ejs:

<% include header %>
<body> . . . </body>
<% include footer%>

header.ejs:

<html lang="en">
<head>
    <title><%- my_tytle %></title>
</head>

footer.ejs:

</html>

How to pass my_title in the include command?


回答1:


You can pass the object inside the include statement

<%- include("header",{title:"your_title"}) %>




回答2:


you can pass my_tytle directly to the index.ejs and if there is a partial view for header, my_tytle should be accessible to the header.

for example: index.ejs:

<% include header %>
<body> . . . </body>
<% include footer%>

header.ejs:

<html lang="en">
<head>
    <title><%- my_tytle %></title>
</head>

now from node server if you pass the value for my_tytle to index.ejs, like this:

res.render('template_file.js', {
        my_tytle : "Value for your title"
    });

then your partial view (i.e header in your case) would be also able to access that variable.



来源:https://stackoverflow.com/questions/23788810/ejs-pass-variable-when-include

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!