当前位置: 动力学知识库 > 问答 > 编程问答 >

Twig & Smarty: object from JSON file

问题描述:

I'm learning both Twig and Smarty and I didn't find an answer for my question for both of them. The question is: is there some built-in way to read variable's value from separate JSON file? I'll use Twig for my examples. OK, this is regular Twig variable definition:

{% set vars = {"foo" : "bar"} %}

Now let's assume that we have a JSON file at /var/www/html/website.com/vars.json that contains:

{

"foo" : "bar"

}

And now I want to initialize my vars with this object, but read it from file instead of definition in the template, something like that:

{% set vars = *some_magic* "/var/www/html/website.com/vars.json" %}

Or, the better example, to use object from the file as include parameter:

{% include "menu.html" with *some_magic* "/var/www/html/website.com/menu.json" only %}

So, is there some build-in way, or, at least, what is the best way to implement it as an extenstion?

网友答案:

You can write your own custom twig function e.g. loadFromJsonFile(filename) and use it like {% set data = loadFromJsonFile('/var/www/html/website.com/menu.json') %}

Here is

  • how to extend twig in symfony 2
  • twig documentation
分享给朋友:
您可能感兴趣的文章:
随机阅读: