【问题标题】:How to display the a line of text in li tag in Django template?如何在 Django 模板的 li 标签中显示一行文本?
【发布时间】:2019-03-08 12:02:12
【问题描述】:

我的 mysql 记录中保存了如下文本:

Handmade item

Materials: wooden handcrafted handle, professional laser engraved rubber, brown 
cardboard special gift box, authorial stamp passport

上面的文字代表了我的配件模型的概述,即:

from django.db import models

class Accessory(models.Model):
    img = models.ImageField(upload_to='accessories/', default='accessories/no.png')
    name = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    img_inside1 = models.ImageField(upload_to='accessories/', default='accessories/no.png', blank=True)
    img_inside2 = models.ImageField(upload_to='accessories/', default='accessories/no.png', blank=True)
    img_inside3 = models.ImageField(upload_to='accessories/', default='accessories/no.png', blank=True)
    title = models.CharField(max_length=50)
    overview = models.TextField(blank=True)
    description = models.TextField()

我想在<li>标签中显示每一行

看起来像这样:

                 <ul>
                    <li><p>Handmade item</p></li>
                    <li><p>Materials: wooden handcrafted handle, 
                       professional laser engraved rubber, brown cardboard 
                      special gift box, authorial stamp passport</p>
                    </li>
                </ul>

使用linebreaks 过滤器将不会应用&lt;ul&gt; 默认样式(显示项目符号)。提前致谢!

【问题讨论】:

  • python代码在哪里?
  • 这里是配件相关的型号from django.db import models class Accessory(models.Model): overview = models.TextField(blank=True) description = models.TextField()
  • 请提出这个python代码
  • 我已经添加了我的python代码

标签: python django python-3.x django-templates


【解决方案1】:

快速而肮脏的解决方案:在换行符上拆分字符串并迭代结果。

class Accessory(models.Model):
    # ...
    overview = models.TextField()

    def overview_lines(self):
        return filter(None, (line.strip() for line in self.overview.splitlines()))

然后

             <ul>
                {% for line in howeryounamedyourobject.overview_lines %}                    
                <li><p>{{ line }}</p></li>
                {% endfor %}
            </ul>

更好的解决方案:

要么有适当的材料模型(多对多关系),要么在“概览”字段中使用标记而不是纯文本。

【讨论】:

    猜你喜欢
    • 2015-07-10
    • 2011-05-14
    • 2019-06-16
    • 2018-09-06
    • 2018-09-03
    • 2021-10-12
    • 2013-04-19
    • 1970-01-01
    • 2021-03-18
    相关资源
    最近更新 更多