copying a property value verbatim

13 views
Skip to first unread message

Julian Lyndon-Smith

unread,
Feb 17, 2015, 4:26:41 PM2/17/15
to nunj...@googlegroups.com
If I have got a variable that is a json array


data
.foo = ["a","b","c"]



and I have this code in my template


{% if data.foo and data.foo.length > 0 %}
 controller
.foo  = {{ data.foo }}
{% endif %}


I get the following code generated;


controller
.foo = a,b,c


whereas I wanted to get


controller
.foo = ["a","b","c"]


is there any way of telling nunjucks to export the variable value as a json string ?


Julian Lyndon-Smith

unread,
Feb 17, 2015, 4:35:48 PM2/17/15
to nunj...@googlegroups.com
and the minute I post, I get an idea of how to do it ...

function JSONStringify(data) {
 
return JSON.stringify(data)
}

data
.JSONStringify = JSONStringify

nj
.render(templateName,data,function(err,res) {
 cb
(err,res)
 
})
}


and in the template


{% if data.foo and data.foo.length > 0 %}

 controller
.foo  = {{ JSONStringify(data.foo) }}
{% endif %}


hope this helps someone

julian
Reply all
Reply to author
Forward
0 new messages