gpt4 book ai didi

symfony - Twig 渲染与包含 - 何时何地使用其中之一?

转载 作者:行者123 更新时间:2023-12-04 01:17:08 24 4
gpt4 key购买 nike

我已阅读 Twig: render vs include但这不是我要找的。我不确定应该在何时何地使用渲染,以及何时应该使用包含,因为这些表达式的行为似乎与我非常相似。

这两个表达之间的根本区别是什么?

最佳答案

{% render %}之间存在较大差异和 {% include %} .

  • {% render %}标签调用一个 Action :当你这样做时,你正在执行一个 Controller ,在该 Controller 内创建一个新的上下文并呈现一个将添加到当前 View 的 View 。
  • {% include %} tag 在当前文件中包含另一个 twig 文件:没有调用任何操作,因此包含的文件将使用您当前的上下文(或您作为参数提供的上下文)来呈现 View 。

  • 让我们详细了解一下。

    {% 渲染 %} 示例

    Render 是一个标签,它调用一个 Action 的方式与你使用路由调用它的方式非常相似,但在内部,没有 HTTP 事务。就个人而言,我正在使用 {% render %}当我的 View 中包含的内容需要使用 ajax 刷新时。这样,当我的页面中有交互时,我可以使用标准路由调用相同的操作。

    考虑一个带有 ajax 表单的简单页面,可以帮助您添加内容,以及一个动态刷新的内容表。

    enter image description here

    东西实体
    <?php

    // src/Fuz/HomeBundle/Entity/StuffData.php

    namespace Fuz\HomeBundle\Entity;

    class StuffData
    {

    private $stuff;

    public function getStuff()
    {
    return $this->stuff;
    }

    public function setStuff($stuff)
    {
    $this->stuff = $stuff;
    return $this;
    }

    }

    东西形式
    <?php

    // src/Fuz/HomeBundle/Form/StuffType.php

    namespace Fuz\HomeBundle\Form;

    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;

    class StuffType extends AbstractType
    {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    $builder->add('stuff', 'text', array('label' => ''));
    }

    public function getDefaultOptions(array $options)
    {
    return array (
    'data_class' => 'Fuz\HomeBundle\Entity\StuffData',
    );
    }

    public function getName()
    {
    return "Stuff";
    }

    }

    routing.yml 文件
    # src/Fuz/HomeBundle/Resources/config/routing.yml

    fuz_home:
    pattern: /
    defaults: { _controller: FuzHomeBundle:Default:index }

    fuz_add_stuff:
    pattern: /add_stuff
    defaults: { _controller: FuzHomeBundle:Default:addStuff }

    fuz_del_stuff:
    pattern: /del_stuff
    defaults: { _controller: FuzHomeBundle:Default:delStuff }

    fuz_list_stuffs:
    pattern: /list_stuffs
    defaults: { _controller: FuzHomeBundle:Default:listStuffs }

    Controller
    <?php

    namespace Fuz\HomeBundle\Controller;

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Fuz\HomeBundle\Entity\StuffData;
    use Fuz\HomeBundle\Form\StuffType;

    class DefaultController extends Controller
    {

    /**
    * Route : fuz_home
    */
    public function indexAction()
    {
    // Initialize some stuffs, stored in the session instead of in a table for simplicity
    if (!$this->get('session')->has('stuffs'))
    {
    $this->get('session')->set('stuffs', array());
    }

    // Create the form used to add a stuff
    $form = $this->createForm(new StuffType(), new StuffData());

    $twigVars = array(
    'formAddStuff' => $form->createView(),
    );

    return $this->render('FuzHomeBundle:Default:index.html.twig', $twigVars);
    }

    /**
    * Route : fuz_add_stuff
    */
    public function addStuffAction()
    {
    $data = new StuffData();
    $form = $this->createForm(new StuffType(), $data);
    $form->bindRequest($this->getRequest());
    if ($form->isValid())
    {
    $stuffs = $this->get('session')->get('stuffs');
    $stuffs[] = $data->getStuff();
    $this->get('session')->set('stuffs', $stuffs);
    }
    return $this->forward("FuzHomeBundle:Default:listStuffs");
    }

    /**
    * Route : fuz_del_stuff
    */
    public function delStuffAction()
    {
    $stuffId = $this->getRequest()->get('stuffId');
    $stuffs = $this->get('session')->get('stuffs');
    if (array_key_exists($stuffId, $stuffs))
    {
    unset($stuffs[$stuffId]);
    $this->get('session')->set('stuffs', array_values($stuffs));
    }
    return $this->forward("FuzHomeBundle:Default:listStuffs");
    }

    /**
    * Route : fuz_list_stuffs
    */
    public function listStuffsAction()
    {
    $stuffs = $this->get('session')->get('stuffs');
    $twigVars = array(
    'stuffs' => $stuffs,
    );
    return $this->render('FuzHomeBundle:Default:listStuffs.html.twig', $twigVars);
    }

    index.html.twig
    {# src/Fuz/HomeBundle/Resources/views/Default/index.html.twig #}

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

    {# The form that will be posted asynchronously #}
    <form id="formStuff">
    {{ form_widget(formAddStuff) }}
    <input type="button" id="add-stuff" value="Add stuff" />
    </form>

    <br/><br/>

    {# The div that will contain the dynamic table #}
    <div id="list-stuffs">
    {% render path('fuz_list_stuffs') %}
    </div>

    {# When a click is made on the add-stuff button, we post the form #}
    <script type="text/javascript">
    $('#add-stuff').click(function() {
    $.post('{{ path('fuz_add_stuff') }}', $('#formStuff').serialize(), function(data) {
    $('#list-stuffs').html(data);
    });
    });
    </script>

    listStuffs.html.twig

    {# listStuf
    fs.html.twig #}

    {% if stuffs | length == 0 %}

    No stuff to display !

    {% else %}

    <table style="width: 50%">

    {% for stuffId, stuff in stuffs %}
    <tr>
    <td>{{ stuff }}</td>
    <td><a data-stuff-id="{{ stuffId }}" class="delete-stuff">Delete</a></td>
    </tr>
    {% endfor %}

    </table>

    <script type="text/javascript">
    $('.delete-stuff').click(function() {
    $.post('{{ path('fuz_del_stuff') }}', {'stuffId': $(this).data('stuff-id')}, function(data) {
    $('#list-stuffs').html(data);
    });
    });
    </script>

    {% endif %}

    这会给你一些看起来像这样的丑陋的形式:

    enter image description here

    关键是:如果您刷新页面或添加/删除内容,将调用相同的 Controller 。无需创建一些复杂的逻辑或复制代码。

    {% include %} 示例
    [% include %}标签可以让你以与 include 相同的方式包含一些 Twig 代码。指令在 PHP 中工作。这基本上意味着: {% include %}为您提供了一种在应用程序中随处重用一些通用代码的方法。

    enter image description here

    我们保留我们的东西示例:保留 StuffEntity 和 StuffData 但替换以下内容:

    路由:
    fuz_home:
    pattern: /
    defaults: { _controller: FuzHomeBundle:Default:index }

    fuz_add_stuff:
    pattern: /add_stuff
    defaults: { _controller: FuzHomeBundle:Default:addStuff }

    fuz_del_stuff:
    pattern: /del_stuff
    defaults: { _controller: FuzHomeBundle:Default:delStuff }

    Controller :
    public function indexAction()
    {
    // Initialize some stuffs, stored in the session instead of in a table for simplicity
    if (!$this->get('session')->has('stuffs'))
    {
    $this->get('session')->set('stuffs', array());
    }

    // Create the form used to add a stuff
    $form = $this->createForm(new StuffType(), new StuffData());
    $stuffs = $this->get('session')->get('stuffs');

    $twigVars = array(
    'formAddStuff' => $form->createView(),
    'stuffs' => $stuffs,
    );

    return $this->render('FuzHomeBundle:Default:index.html.twig', $twigVars);
    }

    /**
    * Route : fuz_add_stuff
    */
    public function addStuffAction()
    {
    $data = new StuffData();
    $form = $this->createForm(new StuffType(), $data);
    $form->bindRequest($this->getRequest());
    if ($form->isValid())
    {
    $stuffs = $this->get('session')->get('stuffs');
    $stuffs[] = $data->getStuff();
    $this->get('session')->set('stuffs', $stuffs);
    }
    return $this->forward("FuzHomeBundle:Default:index");
    }

    /**
    * Route : fuz_del_stuff
    */
    public function delStuffAction()
    {
    $stuffId = $this->getRequest()->get('id');
    $stuffs = $this->get('session')->get('stuffs');
    if (array_key_exists($stuffId, $stuffs))
    {
    unset($stuffs[$stuffId]);
    $this->get('session')->set('stuffs', array_values($stuffs));
    }
    return $this->forward("FuzHomeBundle:Default:index");
    }

    index.html.twig :
    {# src/Fuz/HomeBundle/Resources/views/Default/index.html.twig #}

    <form action="{{ path('fuz_add_stuff') }}" method="post">
    {{ form_widget(formAddStuff) }}
    <input type="submit" value="Add stuff" />
    </form>

    <br/><br/>

    {# Here we include our "generic" table with the stuff table as parameter #}
    {%
    include 'FuzHomeBundle:Default:genericTable.html.twig'
    with {
    'route': 'fuz_del_stuff',
    'data' : stuffs,
    }
    %}

    通用表:
    {# src/Fuz/HomeBundle/Resources/views/Default/genericTable.html.twig #}

    {% if data | length == 0 %}

    No data to display !

    {% else %}

    <table style="width: 50%">

    {% for id, elem in data %}
    <tr>
    <td>{{ elem }}</td>
    <td><a href="{{ path(route, {'id': id}) }}">Delete</a></td>
    </tr>
    {% endfor %}

    </table>

    {% endif %}

    正如您在这里看到的,只有一个 Controller 初始化页面的整个元素(表单和表格),因此不可能进行异步事务。但是,您可以在应用程序的任何位置包含这个 genericTable.html.twig 文件。

    结论

    您将使用 {% render %}当要插入的 View 可以使用标准路由刷新或要插入的 View 完全独立于当前上下文时。

    您将使用 {% include %}当您需要在应用程序中多次使用一段 Twig 代码,但您需要在与父 Twig 文件相同的操作中初始化包含 View 的必需上下文。

    关于symfony - Twig 渲染与包含 - 何时何地使用其中之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16297393/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com