[英]How do I use the external variables from external javascript file into index.pug?
Suppose, I have an external javascript file named myscript.js
. 假设我有一个名为myscript.js
的外部javascript文件。 It declares a variable named headArr
which is an array. 它声明了一个名为headArr
的变量,它是一个数组。
headArr = [`id`,`firstname`,`lastname`,`company`,`salary`];
In the index.pug
, I have an include: 在index.pug
,我包含:
script
include ../public/script/myscript.js
And I use an each
iteration to read each member of the array. 我使用each
迭代来读取数组的每个成员。
ul
each val in headArr
li= val
It returns/shows error that it can't read headArr.length return undefined
它返回/显示it can't read headArr.length return undefined
Then perhaps including your script server-side is an option for you? 那么也许包括您的脚本服务器端是您的选择?
// myscript.js
export const headArr = [`id`,`firstname`,`lastname`,`company`,`salary`];
// Where you do your rendering
import { headArr } from myscript.js
...
await ctx.render(index, { headArr });
Pug allows you to pass in variables as the second argument, which will be bound to window when rendered { test: "something" }
becomes window.test
. Pug允许您传入变量作为第二个参数,当渲染{ test: "something" }
成为window.test
时,该变量将绑定到window。 (ctx.render is just executing the compiledTemplate-function pug has generated); (ctx.render只是在执行已生成的pug已编译的模板函数);
I can find the solution. 我可以找到解决方案。 Thank@ippi In koa.js, you can use require only. Thank @ ippi在koa.js中,您只能使用require。
For my case: In your script add 就我而言:在您的脚本中添加
const head = [`id`,`firstname`,`lastname`,`company`,`salary`];
module.exports.head = head;
Then, index.js add 然后,将index.js添加
const myScript = require('./public/script/myscript');
Then render the page 然后呈现页面
router.get(`/`, async ctx => {
await ctx.render(`index`,myScript)
});
Finally, add the Each iteration to your index.pug file 最后,将“每个迭代”添加到index.pug文件中
tr
each i in head
th= i
router.get(/, async ctx =>
{ await ctx.render ('index', { headArr: headArr} )
});
In your myscript.js file, you can use this code while rendering index.pub. 在myscript.js文件中,可以在渲染index.pub时使用此代码。 Because pug file takes object as a input and you need to pass headArr in that object. 由于pug文件将对象作为输入,因此您需要在该对象中传递headArr。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.