Pass an array as a parameter for view rendering in twig

386 views Asked by At

I'm pretty new to Twig.js, and notice that it lacks some documentation. In fact, I could only find extremely basic usage information on their GitHub wiki.

My views rely on a bunch of variables. All views extend from layout.twig which includes navbar.twig. The last one takes a lot of parameters, like color, names and others I haven't implemented yet.

The problem with this is that I would need to pass lots of variables every time a view gets rendered. So I thought a solution would be to pass an array each time, instead of multiple fieds. My question comes there, as in how I'd interact with this array My current and inefficient solution can be represented when displaying an error:

res.render('error', {title: appConfig.name, color: appConfig.color (...)});

It would be better if I could pass an array and then interact with it inside of my twig view.

I'm open to other solutions. Being able to access appConfig from inside the view would be one of them, although I don't think that is possible. If it this though, please tell me how! I'll thank you forever.

Thanks in advance.

2

There are 2 answers

2
Ben West On BEST ANSWER

Pass appConfig:

var appConfig = { name: 'Jeremy', color: 'green' };
res.render('home', appConfig );

Render it:

<div class="{{ color }}">Hello {{ name }}</div>

Twig can work just fine with nested objects too:

var navConfig = { color: 'salmon' }
res.render('home', { nav: navConfig, name: 'Arnold' })

<nav class="{{ nav.color }}">{{ name }}</nav>
0
Selmi Karim On

You can simply parse appConfig to JSON Object using JSON.parse. Note - JSON.parse can tie up the current thread because it is a synchronous method. So if you are planning to parse big JSON objects use a streaming json parser.