gpt4 book ai didi

python - 以变​​量作为参数的 django 自定义模板过滤器

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:10 25 4
gpt4 key购买 nike

我正在使用 Django 自定义模板过滤器,如所述 here访问我的模板中 3D 数组中的条目。我将 3D 数组 swipeData 从views.py 传递到index.html。

index.html:

function getNearestHalfHourTimeString() {
var now = new Date();
var hour = now.getHours();
var minutes = now.getMinutes();
var ampm = "AM";
if (minutes < 15) {
minutes = "00";
} else if (minutes < 45){
minutes = "30";
} else {
minutes = "00";
++hour;
}
return("T" + hour + minutes);
}

var currentDay = (new Date()).getDay();
var currentTimeRounded = getNearestHalfHourTimeString();

{% block content %}
{% load hello_extras %}
var atrium = {{swipeData|bldIndex:'ATRIUMCAFE'|dayIndex:currentDay|timeIndex:currentTimeRounded }};
{% endblock %}

hello_extras.py:

from django import template

register = template.Library()

@register.filter
def bldIndex(List, strIndex):
dctBuild = {'ATRIUMCAFE':0, 'BUTLERCOLLEGE':1, 'CAFEVIVIAN':2, 'CENTERFORJEWISHLIFE':3, 'CHANCELLORGREEN':4, 'CHEMISTRYCAFE':5, 'CONCESSIONS_12':6, 'FORBESCOLLEGE':7, 'FRISTCSTORE':8, 'FRISTGALLERY1':9, 'FRISTGALLERY2':10, 'FRISTGALLERY3':11, 'FRISTGALLERY4':12, 'FRISTWITHERSPOONS':13, 'GRADUATECOLLEGE':14, 'LIBRARY_CART':15, 'MATHEYCOLLEGE':16, 'ROCKEFELLERCOLLEGE':17, 'STUDIO34BUTLEREMPORIUM':18, 'WHITMANCOLLEGE':19, 'WILSONCOLLEGE':20, 'WOODROWWILSONCAFE':21, 'FIRESTONELIBRARY':22}
i = int(dctBuild.get(strIndex))
return List[i]

@register.filter
def dayIndex(List, strIndex):
return List[int(strIndex)]

@register.filter
def timeIndex(List, strIndex):
dctTime = { "T0000":0, "T0030":1, "T0100":2, "T0130":3, "T0200":4, "T0230":5, "T0300":6, "T0330":7, "T0400":8, "T0430":9, "T0500":10, "T0530":11, "T0600":12, "T0630":13, "T0700":14, "T0730":15, "T0800":16, "T0830":17, "T0900":18, "T0930":19, "T1000":20, "T1030":21, "T1100":22, "T1130":23, "T1200":24, "T1230":25, "T1300":26, "T1330":27, "T1400":28, "T1430":29, "T1500":30, "T1530":31, "T1600":32, "T1630":33, "T1700":34, "T1730":35, "T1800":36, "T1830":37, "T1900":38, "T1930":39, "T2000":40, "T2030":41, "T2100":42, "T2130":43, "T2200":44, "T2230":45, "T2300":46, "T2330":47}
i = int(dctTime.get(strIndex))
return List[i]

我收到错误

VariableDoesNotExist at /
Failed lookup for key [currentDay] in u"[{

如何使用变量作为自定义模板过滤器的参数?我已经尝试过使用 with block 。

最佳答案

你的问题是你试图将 JS var 传递给 django 过滤器,这是错误的

currentDay 和 currentTimeRounded 是 JS 变量而不是 Python 变量,因此过滤器失败

请记住,您可以在 View 中获取所有必要的信息,然后在模板中渲染

我建议您在 View 中格式化数据,并在模板中将其分配给相应的 JS 变量

部分内容如下

def some_view(request):
# here you can calculate, convert, create all values to your chart as you need
# if you need time or date can use datetime module ie

values_to_chart = ""

render(request, template_name, locals())

在你的模板中

var atrium = {{values_to_chart}}

关于python - 以变​​量作为参数的 django 自定义模板过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43793743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com