Задать вопрос

Тел: +7 965 3737 888





CallTag - Just like include, but can pass parameters to it

<p>I knew that template in myght template system can receive some parameters just like a function. And I also want to implement this function in django template. So I finish a rough one, the code is pasted here. It just like include, but in order to distinguish with "include" tag, I call it "call". So you can use it:</p>
{% call "some.html" %}

<p>This way just like include tag, and the advanced way:</p>
{% call "some.html" with "a" "b"|capfirst title="title1" %}
{% call "some.html" with "c" "d" title="title2" %}

<p>So you can see, "call" tag can do like a python function, it can receive tuple parameters and key word parameters, just like the function:</p>
def func(*args, **kwargs):pass

<h1>How to use it</h1>
{% expr "limodou" as name %}
{% call "test/test_sub.html" with "a"|capfirst "b" title="title1" %}&lt;br/&gt;
{% call "test/test_sub.html" with "c" "d" title="title2" %}

<p>expr is also a custom tag written by me. It'll calculate a python expression and save to result to a variable. In this case, the variable it "name".</p>
{% for i in args %}{{ i }}{% endfor %}
&lt;h2&gt;{{ title }}&lt;/h2&gt;
&lt;p&gt;{{ name }}&lt;/p&gt;
{{ args }}
{{ kwargs }}

<p>And you also can see, call tag will auto create args and kwargs context variables.</p>
<p>I hope this will be some useful. </p>

Вопрос полезен? Да0/Нет0

Ответы (6):

Ответ полезен? Да0/Нет0

@albrun the problem is that the keyword is a unicode string. Here's a hack to make it work. Change line 62 to:

a = a.strip().encode('utf8')

Ответ полезен? Да0/Нет0

You can use instead: bits = token.split_contents()

Ответ полезен? Да0/Нет0

bits = token.contents.split() on line 46 doesn't works correctly if you pass string with whitespaces as argument (for example {% call "some.html" with "c" "d e" title="title 2" %}).

Ответ полезен? Да0/Нет0


very good idea this call function. But it have a template error when i send parameters.

Exception Type: TemplateSyntaxError

Exception Value: Caught an exception while rendering: init() keywords must be strings

Do someone have a way to resolved it ??


Ответ полезен? Да0/Нет0

I had to shuffle some variable assignments around to get this to work.

Move: args = [] kwargs = {}

outside of the IF block.

Ответ полезен? Да0/Нет0

very use full ;) thanks