2016-11-05 80 views
0

我正在使用EJS作爲模板引擎,並且想知道如何在頁面佈局的末尾包含僅在一個頁面上需要的腳本。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> 

謝謝!

回答

0

將您的模塊頁面包含在文章標籤中。 <%- 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]