I want to add custom template functions for Pug views.
For simplicity I've created a demo file with one custom function uppercase
:
const Koa = require("koa")
const views = require("koa-views")
const app = new Koa()
app.use(
views(__dirname + "/views", {
extension: "pug",
options: {
helpers: {
uppercase: str => str.toUpperCase()
}
}
})
)
app.use(ctx => ctx.render("index", { name: "Name1" }))
app.listen(3000)
Here is a mega simple template views/index.pug
:
h1= uppercase(name)
But it doesn't work, it prints such error:
TypeError: /Users/max7z/projects/test/t24__test__koa-views_pug/views/index.pug:1
> 1| h1= uppercase(name)
2|
uppercase is not a function
Not using Koa, but I solved a similar issue recently using Eleventy.js with Pug. The Pug documentation is not great on this, so it took a while to figure out.
I had to make the function a global, then use the globals property when rendering the template.
e.g.
global.uppercase = function(str){
return str.toUpperCase();
}
app.use(
views(__dirname + "/views", {
extension: "pug",
options: {
globals: ["uppercase"]
}
})
)