首页 > 解决方案 > Twig Uncaught Twig_Error_Syntax: Unexpected tag

问题描述

这是我第一次使用 Twig,我遇到了一个奇怪的错误:

( ! ) Fatal error: Uncaught Twig_Error_Syntax: Unexpected "post" tag (expecting closing tag for the "for" tag defined near line 21). in /code/site3/views/index/index.twig.php on line 22

我的代码如下:

//Setup The Twig Environment
    $loader = new Twig_Loader_Filesystem('/code/site3/views/');
    $twig = new Twig_Environment($loader);

    //Display The Template
    echo $twig->render('/index/index.twig.php', array('posts' => array('title' => 'A Title', 'content' => 'Abc 123')));

我的html是这样的:

<div class="col-lg-8 col-md-10 mx-auto">
            {% for post in posts %}
                <div class="post-preview">
                    <a href="/posts/view/{% post.post_id %}"> <h2 class="post-title"> {% post.title %}</h2> <h3 class="post-subtitle">  {% post.content %} </h3> </a>
                    <p class="post-meta">
                        Posted by <a href="/profile/{% post.user_id %}">{% post.user.first_name %} {% post.user.last_name %}</a>
                        on {% post.date_created %}
                    </p>
                </div>
                <hr>
            {% endfor %}
        </div>

我在这里可能缺少什么?

标签: phpsymfonytwig

解决方案


看起来你混淆了 Twig 语法{% .. %}用于流控制forif功能,并{{ .. }}用于“回声”。

<div class="col-lg-8 col-md-10 mx-auto">
            {% for post in posts %}
                <div class="post-preview">
                    <a href="/posts/view/{{ post.post_id }}"> <h2 class="post-title"> {{ post.title }}</h2> <h3 class="post-subtitle">  {{ post.content }} </h3> </a>
                    <p class="post-meta">
                        Posted by <a href="/profile/{{ post.user_id }}">{{ post.user.first_name }} {{ post.user.last_name }}</a>
                        on {{ post.date_created }}
                    </p>
                </div>
                <hr>
            {% endfor %}
        </div>

{% .. %}语法用于执行语句,该{{ .. }}语法将表达式的结果打印到模板。


推荐阅读