I know that I can pass variables form the server through the template like this:
//- template.pug
p #{name}'s Pug source code!
and calling as such
pug.renderFile('template.pug', {
name: 'Timothy'
})
(literally copy/pasted from their landing page
But I would like to pass "more complex" variables, for example my pug source may have within it
script.
window.foo = !{foo};
and I want to pass the list of objects:
foo = [{one: 1}, {two: 2}, {three: 3}];
pug.renderFile('template.pug', { foo });
but this produces
<script>
window.foo = [[Object object], [Object object
and so on. Looks like pug (or something in the pipeline) calls "toString" on the input.
I tried to fix it using JSON stringification as Kyle Gillen helpfully answers here, so I wrote this:
script.
window.foo = JSON.parse('!{JSON.stringify(foo)}');
But my foo
variable actually contains lots of '
single-apostrophe characters, so this errors too. And wrapping in "
double quotes is annoying because JSON.stringify
produces JSON with double quotes of course.
I have tried escaping every '
like
script.
window.foo = JSON.parse('!{JSON.stringify(foo).replace(/'/, "\\'")}');
But this has been inconsistent. I think there are other characters or weirdness within the stringification that makes the string end early, I've been getting different errors every time I iteratively try to correct previous ones.
That's why I thought to ask this question, because I'm sure there must be a simpler and better way to do this.
How can I safely pass exactly the same variable from my server to my client through pug?