首页 > 解决方案 > Django 在模板标签中使用变量

问题描述

我正在处理的网站正在使用一个模型作为帖子,另一个链接模型用于将附加到帖子的图像。

page_choices = {
    ('news', 'news'),
    ('activities', 'activities'),
    ('environment', 'environment'),
    ('affairs', 'affairs'),
    ('links', 'links'),
}
link_choices = {
    ('external', 'external'),
    ('none', 'none'),
    ('pdf', 'pdf'),
    ('image', 'image'),
}
class Post(models.Model):
    id = models.AutoField(primary_key=True)
    page = models.CharField(
        choices=page_choices,
        max_length=11,
        default='news',
    )
    title = models.CharField(null=True, max_length = 100)
    content = models.CharField(null=True, max_length = 10000)
    image_filename = models.ForeignKey('Image', on_delete=models.DO_NOTHING, null=True, blank=True)
    has_image = models.BooleanField(default=False)


class Image(models.Model):
    id = models.AutoField(primary_key=True)
    image_file = models.ImageField()
    name = models.CharField(null=True, max_length = 100)
    identifier = models.CharField(null=True, max_length = 100)
    alt_text = models.CharField(null=True, max_length = 100)
    link_address = models.CharField(null=True, blank=True, max_length = 100, help_text="Optional")
    link = models.CharField(
        choices=link_choices,
        max_length=8,
        default='none',
    )

这些模型由视图呈现给 HTML,我正在尝试添加 JS/jQuery 以向图像添加链接功能。我正在尝试获取指向单击图像时应呈现的 pdf 的静态目录的链接。

{% if post.image_filename.link == "pdf" %}
<script>
    $(document).ready(function() {
        $("#{{post.image_filename.identifier}}").click(function() {
            location.href = "{% static 'images/{{ post.image_filename.link_address }}' %}";
        });
    });
</script>
{% endif %}

将 {{ }} 放在模板标签 {% %} 内不起作用,我尝试过使用{% with post.image_filename.link_address as link_address %},但我也无法让它在这种情况下工作:

$("#{{post.image_filename.identifier}}").click(function() {
    location.href = "{% static 'images/post.image_filename.link_address' %}";
});
TemplateSyntaxError 'with' received an invalid token: 'post.image_filename.image_file'

任何指导将不胜感激,谢谢。

标签: javascriptjquerydjangodjango-templates

解决方案


您可以使用|add模板过滤器 [Django-doc]

{% with post.image_filename.link_address as item %}
    location.href = "{% static 'images/'|add:item %}";
{% endwith %}

推荐阅读