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'

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

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

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

最新更新