javascript - 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]:
{% with post.image_filename.link_address as item %}
location.href = "{% static 'images/'|add:item %}";
{% endwith %}
推荐阅读
- azure - 如何使用 terraform 中的 azuread_application 在 azure 中创建服务主体,错误没有足够的权限完成操作
- graphics - 在 DOSBox 下列为支持的无法识别的视频模式
- c# - 具有两个以上嵌套级别的 C# Linq
- shiny - 如何根据公式而不是单元格值更改 Shiny DT 表的单元格颜色?
- javascript - 如何使 JavaScript 忽略对象字段中的转义字符
- angular - Ionic 5 在构建期间将文件导出到 www
- excel - Excel:我可以在“真”时使用“如果”公式,而不必将公式复制到 [value-if-true]?
- java - Java - 带有 Integer.valueOf() 的空格导致 java.lang.NumberFormatException
- jquery - Select2 显示闪烁的“多个”滚动条,直到 ready()
- pyspark - PySpark 自定义 TimestampType 列转换