【问题标题】:Creating 'public functions' in Django / Accessing Model data from current template in template tag在 Django 中创建“公共函数”/从模板标签中的当前模板访问模型数据
【发布时间】:2014-08-01 02:29:41
【问题描述】:

我正在学习 Django,我正在将一个站点从 Laravel 转换为 Django 来帮助我学习。

在 Laravel 中,我有一个代码 sn-p:

public function attr_profile($label)
{
    $attr = space_to_underscore($label);
    if ($this->$attr >= 90) {
        echo '<li>'.$label.'<span class="pull-right label label-highest">'.$this->$attr.'</span></li>';
    } elseif ($this->$attr < 90 && $this->$attr >= 80) {
        echo '<li>'.$label.'<span class="pull-right label label-high">'.$this->$attr.'</span></li>';
    } elseif ($this->$attr < 80 && $this->$attr >= 65) {
        echo '<li>'.$label.'<span class="pull-right label label-normal">'.$this->$attr.'</span></li>';
    } elseif ($this->$attr < 65 && $this->$attr >= 65) {
        echo '<li>'.$label.'<span class="pull-right label label-low">'.$this->$attr.'</span></li>';
    } else {
        echo '<li>'.$label.'<span class="pull-right label label-lowest">'.$this->$attr.'</span></li>';
    }
}

让我使用:

{{ $player->attr_profile('Ball Control') }}
{{ $player->attr_profile('Curve') }}

在模板中,它会吐出:

<li>Ball Control<span class="pull-right label label-highest">95</span></li>
<li>Curve<span class="pull-right label label-high">88</span></li>

我正在尝试以最干燥的方式在 Django 中重复相同的操作。我得到的最接近的是创建一个自定义模板标签。

# Core imports
from django.template import Library

register = Library()

@register.simple_tag
def attr_profile(label):
    attr = label.replace(" ", "_").lower()
    return '<li>' + label + '<span class="pull-right label label-highest">' + attr + '</span></li>'

但理想情况下,我希望能够吐出“self.attr”或“player.attr”,就像我可以在 Laravel 中使用“$this->attr”一样

我尝试了无数次,但每次都失败了。模板标签是做到这一点的最佳方式吗,如果是这样,我该如何在原始模板上使用现有模型?该模板的构建来自:

class PlayerDetailView(DetailView):
    # Define the model for the CBV
    model = Player

如果有帮助

【问题讨论】:

  • 为什么不在{{ object.ball_control }}这样的模板中直接引用玩家的属性呢?
  • 我可以,但是如果标签不是的话,我需要将每个属性包装在 5 中吗?每个对象都在 0-99 之间,并根据它所处的等级获得不同的 CSS 类
  • 为了更好地用代码说明,我在下面添加了一个答案。

标签: python django django-models django-templates


【解决方案1】:

模板sn-ps可以使用include标签,避免使用模板标签。

{% include "label_snippet.html" with label="Ball Control" score=object.ball_control %}

label_snippet.html 的内容可以是:

{% if score >= 90 %}
<li>{{ label }}<span class="pull-right label label-highest">{{ score }}</span></li>
{% elif score < 90 and score >= 80 %}
....
{% endif %}

【讨论】:

  • 我不知道这可能正是我需要的答案!非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 2022-10-04
  • 2015-03-17
  • 1970-01-01
  • 2018-10-21
  • 2023-03-08
相关资源
最近更新 更多