You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Twig实现点击列表项展示对应数据的text属性?

Hey there! Let's break this down clearly for you:

First off, you can't implement this click-to-display interaction with Twig alone. Here's why: Twig is a server-side templating engine—it only handles rendering static HTML from your data on the server, then sends that finished HTML to the browser. Once the page loads, Twig's job is done, and it can't respond to user interactions like clicks that happen in the browser.

But don't worry! We can combine Twig (to build the page structure) with JavaScript (to handle the front-end interaction)—this is a super common approach for this kind of feature.

Step 1: Fix Your Twig Template

Your original Twig had a small bug: the closing </ul> was inside the loop, which would create a new <ul> for every <li>. We'll fix that, and also add a data-text attribute to each <li> to store the corresponding text value for easy access later.

{# Assume your `data` variable is properly passed to the template #}
<ul>
    {% for article in data %}
        <li data-text="{{ article.text }}">
            <a href="#{{ article.id }}">{{ article.id }}</a>
        </li>
    {% endfor %}
</ul>
{# Container to display the selected text #}
<div id="selected-text"></div>

(Note: I added a # to the anchor's href to turn it into a local anchor, preventing accidental page jumps. Adjust this based on your actual needs.)

Step 2: Add JavaScript for the Interaction

Add this script either in a <script> tag at the end of your HTML body, or in an external JS file:

// Grab all list items and the text display container
const listItems = document.querySelectorAll('ul li');
const textDisplay = document.getElementById('selected-text');

// Bind a click event to each list item
listItems.forEach(item => {
    item.addEventListener('click', function() {
        // Pull the text from the data attribute and insert it into the container
        textDisplay.textContent = this.dataset.text;
    });
});

Alternative Approach (Using Stored Data)

If you prefer not to use data-* attributes, you can output your full data set as JSON in the page via Twig, then look up the text by ID with JS:

First, add this to your Twig template:

<script>
    // Pass the server-side data to the browser as a JS variable
    const articles = {{ data|json_encode|raw }};
</script>

Then update your JavaScript:

listItems.forEach(item => {
    item.addEventListener('click', function() {
        // Get the article ID from the anchor's href
        const articleId = parseInt(this.querySelector('a').getAttribute('href').slice(1));
        // Find the matching article in the data set
        const selectedArticle = articles.find(art => art.id === articleId);
        // Display the text
        textDisplay.textContent = selectedArticle.text;
    });
});

This works great if you need to access more than just the text property later on.

内容的提问来源于stack exchange,提问作者Andy88

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:37:34