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

Тел: +7 965 3737 888

456

Просмотров

2

Ответов

ExprTag - Calculating python expression and saving the result to a variable

<p>This tag can be used to calculate a python expression, and save it into a template variable which you can reuse later or directly output to template. So if the default django tag can not be suit for your need, you can use it.</p>
<p>How to use it </p>
{% expr "1" as var1 %}
{% expr [0, 1, 2] as var2 %}
{% expr _('Menu') as var3 %}
{% expr var1 + "abc" as var4 %}
...
{{ var1 }}

<p>for 0.2 version</p>
{% expr 3 %}
{% expr "".join(["a", "b", "c"]) %}

<p>Will directly output the result to template</p>
<p>Syntax </p>
{% expr python_expression as variable_name %}

<p>python_expression can be valid python expression, and you can even use _() to translate a string. Expr tag also can used context variables. </p>

Вопрос полезен? Да0/Нет0
file_4082.py(1.3Кб)
None

Ответы (2):

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

To use the value outside of the block (e.g., outside of the for loop) in which it is set, use

context.dicts[0][self.varname] = eval(self.expr_string, d)

(You could reconfigure the regex to check for "as global" or "as" and set the variable appropriately)

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

This doesn't work inside template blocks in inherited templates (will give errors in dict.update). This update in the node will work on both places:

class ExprNode(template.Node):
    def __init__(self, expr_string, var_name):
        self.expr_string = expr_string
        self.var_name = var_name

    def render(self, context):
        try:
            clist = list(context)
            clist.reverse()
            d = {}
            d['_'] = _
            for c in clist:
                for item in c:
                    if isinstance(item, dict): 
                        d.update(item)
            if self.var_name:
                context[self.var_name] = eval(self.expr_string, d)
                return ''
            else:
                return str(eval(self.expr_string, d))
        except:
            raise