如何将外部.js文件包含到ejs节点模板页面中

编程入门 行业动态 更新时间:2024-10-10 04:27:58
本文介绍了如何将外部.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节点模板页面中

本文发布于:2023-11-28 19:58:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643762.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   如何将   模板   页面   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!