【问题标题】:Manipulate html tags with django template使用 django 模板操作 html 标签
【发布时间】:2014-12-10 22:07:31
【问题描述】:

在我的页面上,我显示来自 3-rt 派对页面的提要并显示文章,我使用 removetags:"b br span a table tbody tr td div strong" 删除所有 unnetsesery html 标签,但有些文章有 img 标签,我喜欢保留它,但我喜欢添加额外的此标签的信息,例如itemprop="image"。 有什么方法可以让我“注入” itemprop="image" 准备好预定义的<img alt="title of image" src="http://example.com/media/k2/items/cache/b2bfbef5bf07350b746434a35b46d416_L.jpg" /> 吗?

例如我对模板中文章的查询:

<div class="media-body">
  <span itemprop="articleSection">{{ object.content|removetags:"b br span a table tbody tr td div strong"|safe|truncatewords_html:56 }}
  </span>
</div>

给了我以下信息:

<div class="media-body">
<span itemprop="articleSection">
<p>
<img class="attachment-full wp-post-image" width="256" height="256" src="http://example.com/wp-content/uploads/2014/10/tt.jpg" alt="tt">
(example.nl) – w końcu zaplanowano rozbudowę lotniska w Eindhoven. Przedsięwzięcie będzie realizowane etapami, tak aby w 2020..............
</p>
<p>Het bericht Dodatkowe loty z lotniska w Eindhoven verscheen eerst op Popolsku.</p>
</span>
</div>

如何将额外的属性itemprop="image"添加到img标签

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    如果您解释您的具体问题、显示一些代码或提供更多信息,我可以向您展示一个使用 Django 的解决方案,但我们可以探索其他解决方案。

    假设我们有这个图像文件:

    <img id="image_id" alt="whatever" src="http://something" />
    

    jQuery

    通过 JQuery,您可以使用 .attr() 向现有元素添加属性,在这种情况下我们可以这样做:

    $('#image_id').attr('itemprop','image')
    

    JavaScript

    在 JavaScript 中,我们有 .setAttribute()

    document.getElementById("question-header").setAttribute('itemprop', 'image')
    

    在这两种情况下,图像都会像这样结束:

    <img itemid="image_id" alt="whatever" src="http://something" itemprop="image"/>
    


    要使用 Django 做这样的事情,我会说你应该创建自己的模板标签,我可以在 Django 中显示一些包含更多信息的东西。

    【讨论】:

    • 感谢您的回复,我更新了更多细节问题
    猜你喜欢
    • 2014-03-20
    • 2021-03-07
    • 2011-06-15
    • 2011-04-16
    • 1970-01-01
    • 2014-12-30
    • 2017-02-16
    • 1970-01-01
    • 2018-01-01
    相关资源
    最近更新 更多