Suppose, I have an external javascript file named myscript.js
. It declares a variable named headArr
which is an array.
headArr = [`id`,`firstname`,`lastname`,`company`,`salary`];
In the index.pug
, I have an include:
script
include ../public/script/myscript.js
And I use an each
iteration to read each member of the array.
ul
each val in headArr
li= val
It returns/shows error that 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
. (ctx.render is just executing the compiledTemplate-function pug has generated);
I can find the solution. Thank@ippi In koa.js, you can use require only.
For my case: In your script add
const head = [`id`,`firstname`,`lastname`,`company`,`salary`];
module.exports.head = head;
Then, index.js add
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
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. Because pug file takes object as a input and you need to pass headArr in that object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.