【问题标题】:How do I use variables as selectors in HMTL/ Bootstrap4?如何在 HTML/Bootstrap 4 中使用变量作为选择器?
【发布时间】:2020-11-12 07:23:47
【问题描述】:

我正在尝试创建一个for 循环以在 Bootstrap 中构建一个手风琴,但每次我单击按钮展开/折叠卡片时,每张卡片都会展开/折叠。我认为这是由于所有卡片共享id,所以我想使用帖子标题作为每张卡片的id 选择器。这是我目前拥有的代码:

  {% for post in blog_posts %}
    <div id="accordion">
      <div class="card">
        <h3 class="card-header" id="header">
          <button class="btn btn-info" data-toggle="collapse" 
          data-target="#body" aria-expanded="false" 
          aria-controls="post: ">
              {{ post.title }}
              <small><p>Posted by {{ post.author }} on 
              {{ post.date_added|date:'D M d, Y H:i' }}</p></small>
          </button>
        </h3>

        <div id="body" class="collapse show" aria-labelledby="header"
          data-parent="#accordion">
          <div class="card-body">
            {{ post.text|linebreaks }}
            <small>
              <a class="text-dark" href="{% url 'blogs:edit_post' post.id %}">
              edit post</a>
            </small>
          </div>
      </div>
    </div>

  {% empty %}
    <p>There are no posts to display.</p>
  {% endfor %}

我尝试将h3 id 更改为{{ post.title }},但这似乎不起作用。非常感谢任何帮助。

【问题讨论】:

  • id="{{ post.title }}" id 放的时候是什么样子的?

标签: python html django bootstrap-4


【解决方案1】:

示例代码: https://getbootstrap.com/docs/4.0/components/collapse/#accordion-example

您需要每个手风琴部分的 id 是唯一的(否则它们将同时打开),您可以使用 post.id。

{% if blog_posts %}
<div id="accordion">
  {% for post in blog_posts %}
      <div class="card">
        <h3 class="card-header" id="header-{{post.id}}">
          <button class="btn btn-info" data-toggle="collapse" 
          data-target="#post-{{post.id}}" aria-expanded="false" 
          aria-controls="post-{{post.id}}">
              {{ post.title }}
              <small><p>Posted by {{ post.author }} on 
              {{ post.date_added|date:'D M d, Y H:i' }}</p></small>
          </button>
        </h3>

        <div id="post-{{post.id}}" class="collapse show" aria-labelledby="header-{{post.id}}"
          data-parent="#accordion">
          <div class="card-body">
            {{ post.text|linebreaks }}
            <small>
              <a class="text-dark" href="{% url 'blogs:edit_post' post.id %}">
              edit post</a>
            </small>
          </div>
      </div>
  {% endfor %}
</div>

{% else %}
    <p>There are no posts to display.</p>
{% endif %}

【讨论】:

  • 我不会使用“primary-key-value-only”作为 HTML id,因为其他模型的污点很容易创建并且很难发现。所以添加一个前缀 (post-),就像你对 aria-labelledby 所做的那样。
  • 同意,我正要对示例进行更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
相关资源
最近更新 更多