EJS在页面布局的开始/结束处包含脚本

EJS include script at start/end of page layout

本文关键字:结束 包含 脚本 开始 布局 EJS      更新时间:2023-09-26

我正在使用EJS作为模板引擎,我想知道如何在页面布局的末尾包含一个只需要在一个页面上的脚本。

的例子:布局:

<head>
   //Scripts and stuff
</head>
<body>
   <article>
     <%-body%> // Render page here
   </article>
</body>

页面:

    //This script needs to go within the head of the layout
    //Or before the closing </body> tag in the layout, but only
    //when this particular page is loaded.
    <script src="onlyRequiredOnThisPageWithinTheLayout.js"></script> 
    <p>Page content</p>

谢谢!

将您的模块页面包含在文章标签中。<%- include("page.ejs") %>

在布局的头标签里面写一个脚本把<script></script>标签附加到head标签上

layout.ejs

    <head>
    <script>
    function clean(){
        sc=document.querySelectorAll(".pagescript");
        head=document.getElementsByTagName("head");
        for(s=0;s<sc.length;s++){
          head[0].appendChild(sc[s]);
         }
        }
    document.addEventListener( "DOMContentLoaded", clean, false );
   </script>    
   </head>
    <body>
       <article>
         <%- include("page.ejs") %> // Render page here
       </article>
    </body>
你page.ejs

<script class="pagescript" src="onlyRequiredOnThisPageWithinTheLayout.js"></script> 
    <p>Page content</p>

我已经采取循环追加脚本标签,使用sc[0],如果你只有一个脚本标签。