简体   繁体   English

NODE.JS访问EJS模板中的函数

[英]NODE.JS accessing functions within an EJS template

I have a scripts.js file that includes a function inside that i want to access within an EJS templates. 我有一个scripts.js文件,其中包含要在EJS模板中访问的函数。

in the templates i included a header, in the header I added a script rel to scripts.js 在模板中,我包含一个标题,在标题中,我向scripts.js添加了一个脚本rel

<script src="/scripts/scripts.js" type="text/javascript"></script> 

I tested it though console.log("test") and when the template is being called I see "test" appears in the console. 我通过console.log(“ test”)对其进行了测试,并且在调用模板时,我看到“ test”出现在控制台中。

when I try to call an actual function (verify_data) within the EJS template i get an error verify_data is not defined. 当我尝试在EJS模板中调用实际函数(verify_data)时,出现错误verify_data未定义。 the error code within the EJS looks like this: EJS中的错误代码如下所示:

<p><em>Submited By <%= verify_data(results.user.username) %></em></p>

the function check if the argument passed is null/undefined, if yes the data returns if not "n/a" string returns instead. 该函数检查传递的参数是否为null / undefined,如果是,则返回数据,否则返回“ n / a”字符串。

How do i access JS functions directly within EJS template ? 如何直接在EJS模板中访问JS函数?

Thanks, 谢谢,

Assuming you're not using a SPA framework, you need to add a tag which will be either replaced by the function or to contain the data you want to store. 假设您不使用SPA框架,则需要添加一个标签,该标签将被该函数替换或包含要存储的数据。

Look at this code snippet 看看这个代码片段

 <p><em>Submited By <span id='userData'></span></em></p> <script> //This is the script.js function verify_data(userName) { return `My data with '${userName}'`; } </script> <script> let data = verify_data("EleFromStack"); // assuming <%=results.user.username%> = "EleFromStack" document.querySelector("#userData").textContent = data; </script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM