pattern-lab / patternengine-php-twig

Twig-based PatternEngine for Pattern Lab.
http://patternlab.io/
MIT License
78 stars 36 forks source link

Import variables from several jsons #6

Closed TxHawks closed 9 years ago

TxHawks commented 9 years ago

Is it possible to import variables for a pattern from several json files? I'm building a rather complex app where a page inherits from the section it reside in.

I'd like to have json files for each section and do something like:

// article~news.json
{
  "section": "news"
}
{# article.twig#}
{% if section == "news" %}
  {# code to import variables from '_data/section-news.json' #}
{% endif %}
dmolsen commented 9 years ago

It's too late to import data once you're rendering the template. Anything in _data should be imported regardless.

If you're trying to only use data from section-news.son I think you're going to have to look into Twig's merge function. I haven't tested this at all but you could have _data/section-news.json look like:

{ "section-news: { "news": {
    "articles": [ { "title": "foo", "body": "lorem" }, { "title": "bar", "body": "ipsum" } ]
} } }

And then:

{% if section == "news" %}
    {% set _context = _context|merge(_context.section-news) %}
{% endif %}

That should bubble up the section-news stuff to the top of the context stack.

TxHawks commented 9 years ago

@dmolsen -

Thanks, didn't know that anything in _data gets imported.

Though , from a very simple test I ran, I think there is no need to merge - any key defined in a json that resides inside _data is already part of _context.

dmolsen commented 9 years ago

That's a "new" feature that hasn't been documented.