有没有办法在第二个循环中渲染 Twig 块?

发布于 2025-01-13 16:23:16 字数 1267 浏览 4 评论 0原文

假设我们在整个内容页面上传播新闻帖子的预告片。其中一些是由编辑器设置的,所有其他的应该动态加载。动态加载器必须尊重编辑器设置的新闻,以免多次显示相同的新闻。

棘手的部分是编辑器将新闻放置在动态区域之后。

我尝试做的是渲染除动态部分之外的整个页面,收集设置新闻的ID以将它们从延迟块中的动态新闻中排除。

用代码说话:

我们的页面有以下模板:

<div class="container">
    {# AREA 1 – dynamic area that should not show news with ID 1 #}
    {% include 'news-dynamic.html.twig' %}

    {# AREA 2 – contains news with ID 1, set by editor #}
    {% include 'news-static.html.twig' %}
</div>

news-dynamic.html.twig 的内容:

{# news_id_loaded_by_service – must not have the ID 1 #}
{%- set news_id_loaded_by_service = get_relevant_news(seen_news) -%}
{%- do seen_news.append(news_id_loaded_by_service) -%}

{# HTML – deferred #}
<pre>{{ seen_news|join(', ') }}</pre>
<pre>{{ news_id_loaded_by_service }}</pre>
<hr>

news-static.html.twig 的内容>:

{%- set news_id_set_by_editor = 1 -%}
{%- do seen_news.append(news_id_set_by_editor) -%}

{# HTML – rendered instantly #}
<pre>{{ seen_news|join(', ') }}</pre>
<pre>{{ news_id_set_by_editor }}</pre>
<hr>

所需输出:

2, 1
2
---
2, 1
1
---

Let‘s say we spread teasers of news posts all over a content page. Some of them are set by the editor and all others should be dynamically loaded. The dynamic loader has to respect the news that are set by the editor to not show the same news multiple times.

The tricky part is when the editor places a news after a dynamic area.

What I try to do is to render the whole page except the dynamic parts, collect the IDs of the set news to exclude them from the dynamic ones in the deferred blocks.

Speaking in Code:

Our page has the following template:

<div class="container">
    {# AREA 1 – dynamic area that should not show news with ID 1 #}
    {% include 'news-dynamic.html.twig' %}

    {# AREA 2 – contains news with ID 1, set by editor #}
    {% include 'news-static.html.twig' %}
</div>

Content of news-dynamic.html.twig:

{# news_id_loaded_by_service – must not have the ID 1 #}
{%- set news_id_loaded_by_service = get_relevant_news(seen_news) -%}
{%- do seen_news.append(news_id_loaded_by_service) -%}

{# HTML – deferred #}
<pre>{{ seen_news|join(', ') }}</pre>
<pre>{{ news_id_loaded_by_service }}</pre>
<hr>

Content of news-static.html.twig:

{%- set news_id_set_by_editor = 1 -%}
{%- do seen_news.append(news_id_set_by_editor) -%}

{# HTML – rendered instantly #}
<pre>{{ seen_news|join(', ') }}</pre>
<pre>{{ news_id_set_by_editor }}</pre>
<hr>

Desired output:

2, 1
2
---
2, 1
1
---

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文