【问题标题】:Improve the function of a template tag - Django改进模板标签的功能 - Django
【发布时间】:2020-04-16 08:29:55
【问题描述】:

我正在编写一个星级评分系统,以图形方式计算课程的星级,我使用了以下模板标签:

@register.simple_tag
def get_course_rating(course):
    decimal, integer = math.modf(course.get_average_rating())

    rating_stars = {
        'stars': range(int(integer))
    }

    if decimal > 0:
        rating_stars['star_half_empty'] = True
        rating_stars['stars_empty'] = range((5 - int(integer)) - 1)
    else:
        rating_stars['star_half_empty'] = False
        rating_stars['stars_empty'] = range(5 - int(integer))

    return rating_stars

通过这种方式,我将星级评分放在 HTML 中:

{% load course_tags %}
{% get_course_rating course as rating %}

{% for i in rating.stars %}
    <i class="icon-star"></i>
{% endfor %}

{% if rating.star_half_empty %}
    <i class="icon-star-half-alt"></i>
{% endif %}

{% for i in rating.stars_empty %}
    <i class="icon-star-empty"></i>
{% endfor %}

我觉得这样做很乏味,所以我想知道是否有办法改进它? 在 HTML 的意义上。

我使用这个 html 代码大约 3 次,对我来说这是重复的代码,我不希望这样......

我突然想到模板标签返回 html 代码,但我不确定这是否是好的做法......

还有更专业的解决方案吗?这对我的学习有很大帮助...

【问题讨论】:

  • 您可以将此星标 html 作为单独的模板,并通过include 重复使用它。或者把它做成单独的inclusion_tag
  • 最好的解决方案是包含标签!谢谢!!

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


【解决方案1】:

您可以将此"start rating html" 作为单独的模板并将其与自定义inclusion tag 一起使用

另一个不太动态的选项 - 在模板中重复使用include

区别nicely described here

【讨论】:

  • 将文件保存在以下路径中:courses/snippets/rating_stars.html。你怎么看?
  • 这个html是模板,所以它应该去templates目录(你选择的子目录)。标签定义 - 在templatetags.
  • 我忘了放完整的路线,这里是:courses/templates/courses/snippets/rating_stars.html。就这样好吗?你怎么看?
  • 是的,没关系。目录布局更多的是个人品味,应该对您有意义。即,我更喜欢具有多个应用程序的 django 项目 - 一个通用模板目录(因为这些模板定义了我的网站的外观)(带有应用程序的子目录),因此应用程序目录中没有模板。但是,在这种情况下 - 模板是模板标签的一部分,不应该直接使用。模板标签在某些应用程序中。所以,这个模板需要在这个app dir/templates dir中,而不是在common templates dir中。
  • 简而言之,这个模板必须在应用程序的“templates”目录下,模板标签在哪里,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 1970-01-01
  • 2011-02-09
  • 2013-01-21
  • 2012-10-31
相关资源
最近更新 更多