django自定义模板过滤器,带变量作为参数

时间:2017-05-04 22:28:16

标签: python html django django-templates django-template-filters

我使用了here所述的Django自定义模板过滤器来访问模板中3D数组中的条目。我将来自views.py的3D数组swipeData传递给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了。

1 个答案:

答案 0 :(得分:1)

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

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

请记住,您可以在视图中获取所有必要信息,然后在模板中进行渲染

我建议您在视图和模板中格式化数据,将其分配给相应的JS var

一些如下

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}}