【问题标题】:Django using variables in Template TagDjango 在模板标签中使用变量
【发布时间】:2021-06-02 12:07:58
【问题描述】:

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

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'

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

【问题讨论】:

    标签: javascript jquery django django-templates


    【解决方案1】:

    您可以使用|add template filter [Django-doc]

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

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 2021-02-15
      • 2014-03-20
      • 2011-10-04
      相关资源
      最近更新 更多