Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swig (node.js) Include a File and pass an object

I am facing this problem.

I've got a page with an include of another like this:

index.html

{{ set pets = { pets : petsObject } }}
{{ include pets.html }}

petsObject is an object like this

petsObjects: [
{ name : "cat" },
{ name : "dog" }
]

When I try to render the page I get a blank page with only this:

[object Object]

I have no clue about what is going on :(

Thanks in advance!

like image 825
turik Avatar asked Jan 12 '23 21:01

turik


1 Answers

Seems you'll need to use:

{% include pets.html with pets %}

According to docs for include:

Locally declared context variables are not passed to the included template by default.

It is also recommended for performance to use the only keyword after the included terms, like this:

{% include pets.html with pets only %}

Beyond that, it depends on the contents of pets.html, which you haven't included here. But, make sure that you're attempting to output the name:

{% for pet in pets %}
  {{ pet.name }}
{% endfor %}

Or use a filter like json_encode() to format it:

{% for pet in pets %}
  {{ pet|json_encode }}
{% endfor %}

Trying to output the Objects themselves will simply produce [object Object]:

new Object().toString() === "[object Object]"
like image 112
Jonathan Lonowski Avatar answered Jan 27 '23 04:01

Jonathan Lonowski