我有这样构造的数组
add_to_context('custom', [
[
'title' => 'My title',
'link' => 'My link'
],
[
'title' => 'My title 1',
'link' => 'My link 1'
]
]);
Run Code Online (Sandbox Code Playgroud)
鉴于我有简单的循环
{% for item in custom %}
<li>
<h1>{{ item.title }}
<img src="{{ item.link|e }}" target="_blank">
</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
而且一切正常。但是我想打印两个键都带有值的元素。例如,如果我有
[
'title' => '',
'link' => 'mylink'
]
Run Code Online (Sandbox Code Playgroud)
我不想打印这个。如果链接为空,我也不要。如果两者都为空-相同。我只想在两个键都有值的情况下打印它。那么,我该怎么做呢?
小智 5
You could do something like this, maybe.
Twig even has a little built in functionality for this:
<ul>
{% for item in custom if item.title and item.link %}
<li>{{ item.title }}</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
I haven't tested it, but I assume the and in the if statement should work.