【问题标题】:Create Twig variables from Twig array从 Twig 数组创建 Twig 变量
【发布时间】:2017-09-23 10:44:30
【问题描述】:

我正在使用带有 Twig 的 codeigniter - 我正在尝试创建一个动态选择框,其中包含来自数据库的数据。

这就是我现在正在做的事情

      // animals is $data['animals']=$this->loadmodel->some_function()
      // animals passed from the controller ...


           <select  id="foo" class="form-control">
                <option selected="true" >Animals</option>
                   {%  for animal_key in animals %}
                      <option >
                     {{ animal_key ["animal_description"] }}
                     </option>
                   {% endfor %}
             </select>

所以以上一切都运作良好。但是如果我想让它动态呢?每个选择框从控制器中的不同方法获取数据 - 假设我有来自其他方法的数据 - 就像这里

       // orders is $data['orders']=$this->loadmodel->some_function()
       // orders passed from the controller ...

           <select  id="foo" class="form-control">
                <option selected="true" >orders</option>
                   {%  for order_key in orders%}
                      <option >
                     {{ order_key ["order_description"] }}
                     </option>
                   {% endfor %}
             </select>

             <select  id="foo" class="form-control">
                <option selected="true" >Animals</option>
                   {%  for animal_key in animals %}
                      <option >
                     {{ animal_key ["animal_description"] }}
                     </option>
                   {% endfor %}
             </select>

我的想法是做这样的事情:

设置控制器名称数组:

         {% set controller_names = ['animals','orders']%}

设置控制器变量及其键的数组:

         {% set controller_vars = 
           ['animals'=>'animal_description','orders'=>'order_description']%}

然后像这样迭代它

         {%  for names in controller_names  %}
              <select  id="foo" class="form-control">
                <option selected="true" >{{ name }}</option>
                   {%  for controller_key in controller_vars %}
                      <option >
                     {{ controller_vars [ controller_key] }} //suppose to be Twig variables
                     </option>
                   {% endfor %}
             </select>
         {% endfor %} 

所以我需要将设置的 controller_vars 数组转换为 Twig 变量(只要可能).....

【问题讨论】:

    标签: php codeigniter twig


    【解决方案1】:

    你可以使用attribute函数:

                   {%  for controller_key in controller_vars %}
                      <option >
                        {{ attribute(controller_key, controller_vars) }}
                     </option>
                   {% endfor %}
    

    希望有帮助

    【讨论】:

    • 谢谢 - 但它不起作用......你能给我一个扩展的例子吗?
    • 嗨@RoyBarOn 对不起,我在示例中犯了一个错误:我反转了属性函数的参数(我更新了我的答案)你可以试试吗?
    • 对不起 - 不起作用 - 我试图“告诉” twig 键和值是 php 变量....
    • 嗨@RoyBarOn 可能我不明白你的问题,你能用twigfiddle 复制吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    相关资源
    最近更新 更多