在Django中创建“public functions”/在template tag中从当前模板访问模型数据

2024-05-01 22:09:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学习Django的过程中,我正在将一个网站从Laravel转换成Django来帮助我学习。你知道吗

在拉威尔,我有一段代码:

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>'

但理想的情况是我想吐出来自身属性'或'播放器.attr'比如我如何在拉威尔使用'$this->;attr'

我试过无数次,但每次都是摔倒在地。模板标记是实现这一点的最佳方法吗?如果是,如何在原始模板上使用现有模型?模板的构建依据:

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

如果有帮助的话


Tags: djangoechoright模板lithisprofilepull
1条回答
网友
1楼 · 发布于 2024-05-01 22:09:34

可以对模板片段使用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 %}

相关问题 更多 >