变量作为 TWIG 中的行名称:Symfony 2 [英] Variable as name of row in TWIG : Symfony 2

查看:27
本文介绍了变量作为 TWIG 中的行名称:Symfony 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Symfony2 应用程序有问题.在 Controller 中,我获取了一组 facebook 用户并将其发布到我的表单类中,在那里我创建了一些复选框.在我的模板中,我需要将这些复选框打印为这些用户的图片.我尝试像这样打印它:{{form_row(form.{{girl.id}})}},但 TWIG 模板不允许使用变量 {{girl.id}} 作为行名,而且我也不允许不知道如何将这些复选框打印为图片.谁能帮我这个 ?

I have a problem in my Symfony2 application. In Controller I'm getting an array of facebook users and posting it to my form class, where I create some checkboxes. In my template I need to print theese checkboxes as pictures of these users. I try to print it like this : {{form_row(form.{{girl.id}})}}, but TWIG template doesn't allow to use variable {{girl.id}} as name of row and also I don't know how print theese checkboxes as pictures. Can anyone help me with this ?

这是一个控制器动作

public function indexAction()
    {

        $facebook = $this->get('facebook');
        $friends = $facebook->api('me/friends?fields=id,name,gender');

        $friends = $friends['data'];
        foreach($friends as $friend){

            if(array_key_exists('gender',$friend))
            {
            if($friend['gender'] =='female')
                $girls[]=$friend;
            }
            }
            for ($i=0; $i <5; $i++) { 
                $default[]=$girls[$i];
            }
        $formular = new FriendsForm();
        $formular->addFriend($default);

        $form = $this->createForm($formular);




        return array('girls'=>$default,'form' => $form->createView());
    }

这是我的表单类

class FriendsForm extends AbstractType
{
    private $friends;

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $friends = $this->friends;

        foreach($friends as $friend)
        {
            $builder
            ->add($friend['id'],'checkbox',array('label' => false,'required'=>false, 'value'=>$friend['']));
        ;    
        }

    }


    public function getName()
    {
        return '';

    }

     public function addFriend($data)
    {
        $this->friends = $data;
    }

}

这是我的模板

<p>
{%if girls is defined%}
{{form_start(form)}}
{%for girl in girls%}
{{form.row(form.{{girl.id}})}}
{%endfor%}
{{form_end(form)}}
{%endif%}
</p>

推荐答案

您可以使用 attribute 内置函数(从 1.2 开始).

You can use attribute built-in function (as of 1.2).

http://twig.sensiolabs.org/doc/functions/attribute.html

属性可用于访问变量的动态"属性

attribute can be used to access a "dynamic" attribute of a variable

在这种情况下,您可以像下面这样写:

In such case you can write like below:

{{ form_row(attribute(form, girl.id)) }}

这篇关于变量作为 TWIG 中的行名称:Symfony 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆