如何将外部.js文件包含到ejs节点模板页面中 [英] How to include external .js file to ejs Node template page

查看:326
本文介绍了如何将外部.js文件包含到ejs节点模板页面中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到将外部.js文件包含到Node ejs模板中的方法.我想将逻辑和数据放入外部.js文件中的对象中,将该文件包含到index.ejs模板中,然后从其中提取数据.

I cannot find a way to include external .js file to Node ejs template. I want to put logic and data into object in external .js file, include that file to index.ejs template and pull data from it.

我尝试通过插入标准方式 <script src="sample.js"></script>,它不起作用

I tried by inserting standard way <script src="sample.js"></script>, and it doesn't work

然后,我尝试使用ejs专用关键字<% include partials/sample.js %>,这仅适用于添加部分内容(ejs代码段).

Then I tried ejs specific keyword <% include partials/sample.js %> and this works only for adding partials (ejs code snippets).

我将.js文件插入了在可执行server.js中定义的静态目录中,再次没有结果.

I inserted .js file into static directory which is defined in executable server.js, no results again.

但是有趣的是,例如,将css文件包含到ejs模板的经典方法中可以很好地工作

But interestingly, including css file into ejs template classic way works fine, for example

<link href="/assets/styles.css" rel="stylesheet" type="text/css" />

解决方法是包括外部ejs文件,在其中我将逻辑和数据放在<%%>标记内,但这显然是一个补丁程序,而不是可行的解决方案,因为ejs不是js文件.此外,它不起作用.

Workaround would be to include external ejs file where I would put logic and data inside <% %> tags, but this is obviously a patch and not a viable solution, because ejs is not a js file. Besides, it doesn't work.

我在Internet上找不到任何解决方案.有提示吗?

I cannot find any solution on Internet. Any hint?

谢谢

推荐答案

您不能.

注意:您只能将数据从.ejs文件传递到.js文件,而不能以其他方式传递.它不起作用,因为.ejs在服务器端呈现,而.js在客户端运行. 我假设您正在服务器端使用EJS

Note: You can only pass data from .ejs file to .js file but not the other way. It won't work because .ejs is rendered on the server side while .js runs on the client side. I am assuming you are using EJS on server side

1)您可以将ejs变量值传递给Javascript变量

1) You can pass an ejs variable value to a Javascript variable

    <% var test = 101; %> // variable created by ejs
    <script>
       var getTest = <%= test  %>;  //var test is now assigned to getTest which will only work on browsers
       console.log(getTest);  // successfully prints 101 on browser
    </script>

2)您不能将js变量值传递给ejs变量

2) You can't pass a js variable value to a ejs variable

是的,您不能:如果它在服务器上.

为什么:

EJS模板将在开始执行js之前在服务器上呈现(它将在浏览器上启动),因此无法返回到服务器并要求页面上已发送到页面的先前更改.浏览器.

The EJS template will be rendered on the server before the js is started execution(it will start on browser), so there is no way going back to server and ask for some previous changes on the page which is already sent to the browser.

这篇关于如何将外部.js文件包含到ejs节点模板页面中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆