这是我第一次使用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>
我在这里可能会想念什么?
答案 0 :(得分:3)
好像您混合了Twig语法{% .. %}
用于for
和if
函数之类的流控制,而{{ .. }}
用于“ echoing”。
<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>
{% .. %}
语法用于执行语句,{{ .. }}
语法将表达式的结果打印到模板。