Programming

템플릿 코드 내에서 변수 값을 설정하는 방법은 무엇입니까?

procodes 2020. 5. 14. 21:00
반응형

템플릿 코드 내에서 변수 값을 설정하는 방법은 무엇입니까?


템플릿이 있다고 가정 해보십시오.

<html>
<div>Hello {{name}}!</div>
</html>

테스트하는 동안이 템플릿을 호출하는 파이썬 코드를 건드리지 않고 변수 값을 정의하는 것이 좋습니다. 그래서 나는 이런 것을 찾고 있습니다

{% set name="World" %}     
<html>
<div>Hello {{name}}!</div>
</html>

장고에 이런 것이 있습니까?


with템플릿 태그를 사용할 수 있습니다 .

{% with name="World" %}     
<html>
<div>Hello {{name}}!</div>
</html>
{% endwith %}

템플릿 태그를 만듭니다.

이 앱은 포함해야 templatetags같은 수준에서, 디렉토리 models.py, views.py잊어하지 않습니다 - 등이 이미 존재하지 않는 경우를 만들 __init__.py디렉토리가 파이썬 패키지로 처리하기 위해 파일을.

다음 코드를 사용하여 templatetags 디렉토리 define_action.py내에 이름이 지정된 파일을 작성하십시오 .

from django import template
register = template.Library()

@register.assignment_tag
def define(val=None):
  return val

참고 : 개발 서버는 자동으로 다시 시작되지 않습니다. templatetags모듈을 추가 한 후 템플릿에서 태그 또는 필터를 사용하려면 서버를 다시 시작해야합니다.


그런 다음 템플릿에서 다음과 같이 컨텍스트에 값을 할당 할 수 있습니다.

{% load define_action %}
{% if item %}

   {% define "Edit" as action %}

{% else %}

   {% define "Create" as action %}

{% endif %}


Would you like to {{action}} this item?

"with"블록에 모든 것을 넣을 필요가없는 다른 방법은 컨텍스트에 새 변수를 추가하는 사용자 정의 태그를 작성하는 것입니다. 에서처럼 :

class SetVarNode(template.Node):
    def __init__(self, new_val, var_name):
        self.new_val = new_val
        self.var_name = var_name
    def render(self, context):
        context[self.var_name] = self.new_val
        return ''

import re
@register.tag
def setvar(parser,token):
    # This version uses a regular expression to parse tag contents.
    try:
        # Splitting by None == splitting by spaces.
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
    m = re.search(r'(.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name
    new_val, var_name = m.groups()
    if not (new_val[0] == new_val[-1] and new_val[0] in ('"', "'")):
        raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
    return SetVarNode(new_val[1:-1], var_name)

이를 통해 템플릿에 다음과 같은 내용을 작성할 수 있습니다.

{% setvar "a string" as new_template_var %}

이것의 대부분은 여기 에서 가져온 것입니다


There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
Because of this, the recommended way to change any variable is via touching the Python code.


The best solution for this is to write a custom assignment_tag. This solution is more clean than using a with tag because it achieves a very clear separation between logic and styling.

Start by creating a template tag file (eg. appname/templatetags/hello_world.py):

from django import template

register = template.Library()

@register.assignment_tag
def get_addressee():
    return "World"

Now you may use the get_addressee template tag in your templates:

{% load hello_world %}

{% get_addressee as addressee %}

<html>
    <body>
        <h1>hello {{addressee}}</h1>
    </body>
</html>

Perhaps the default template filter wasn't an option back in 2009...

<html>
<div>Hello {{name|default:"World"}}!</div>
</html>

This is not a good idea in general. Do all the logic in python and pass the data to template for displaying. Template should be as simple as possible to ensure those working on the design can focus on design rather than worry about the logic.

To give an example, if you need some derived information within a template, it is better to get it into a variable in the python code and then pass it along to the template.


Use the with statement.

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.


In your template you can do like this:

{% jump_link as name %}
{% for obj in name %}
    <div>{{obj.helo}} - {{obj.how}}</div>
{% endfor %}

In your template-tags you can add a tag like this:

@register.assignment_tag
def jump_link():
    listArr = []
    for i in range(5):
        listArr.append({"helo" : i,"how" : i})
    return listArr

참고URL : https://stackoverflow.com/questions/1070398/how-to-set-a-value-of-a-variable-inside-a-template-code

반응형