jinja2에서 파이썬 함수 호출
저는 jinja2를 사용하고 있으며, 매크로를 호출하는 것과 유사한 구문을 사용하여 python 함수를 도우미로 호출하고 싶습니다.jinja2는 함수 호출을 막으려는 의도로 보이며 함수를 매크로로 템플릿에 복사하여 반복한다고 주장합니다.
이것을 할 수 있는 간단한 방법이 있습니까?그리고, 전체 파이썬 함수 세트를 가져와서 많은 리가마롤(확장자 작성 등)을 거치지 않고 jinja2에서 액세스할 수 있는 방법이 있습니까?
플라스크를 사용하는 사람들을 위해, 이것을 당신의 안에 넣으세요.__init__.py
:
def clever_function():
return u'HELLO'
app.jinja_env.globals.update(clever_function=clever_function)
템플릿에서 다음과 같이 호출합니다.{{ clever_function() }}
참고: 플라스크 전용입니다!
이 게시물이 꽤 오래된 것은 알지만, 상황에 맞는 프로세서를 사용하는 최신 버전의 플라스크에서 이를 수행하는 더 나은 방법이 있습니다.
변수는 쉽게 생성할 수 있습니다.
@app.context_processor
def example():
return dict(myexample='This is an example')
위의 내용은 다음과 같은 플라스크를 사용하여 진자2 템플릿에서 사용할 수 있습니다.
{{ myexample }}
(출력 대상This is an example
)
완전한 기능뿐만 아니라 다음과 같은 기능도 제공합니다.
@app.context_processor
def utility_processor():
def format_price(amount, currency=u'€'):
return u'{0:.2f}{1}'.format(amount, currency)
return dict(format_price=format_price)
위의 내용을 이렇게 사용할 경우:
{{ format_price(0.33) }}
(통화 기호가 포함된 입력 가격을 출력합니다.
또는 플라스크에 구운 진자 필터를 사용할 수 있습니다.예: 장식자 사용:
@app.template_filter('reverse')
def reverse_filter(s):
return s[::-1]
또는 데코레이터 없이 수동으로 기능을 등록할 수도 있습니다.
def reverse_filter(s):
return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter
위의 두 가지 방법으로 적용된 필터는 다음과 같이 사용할 수 있습니다.
{% for x in mylist | reverse %}
{% endfor %}
저는 jinja가 일부러 템플릿 내에서 '임의' 파이썬을 실행하는 것을 어렵게 만든다고 생각합니다.템플릿의 논리가 적으면 좋은 것이라는 의견을 강요하려고 합니다.
내부의 글로벌 네임스페이스를 조작할 수 있습니다.Environment
함수에 대한 참조를 추가하는 인스턴스입니다.템플릿을 로드하기 전에 이 작업을 수행해야 합니다.예:
from jinja2 import Environment, FileSystemLoader
def clever_function(a, b):
return u''.join([b, a])
env = Environment(loader=FileSystemLoader('/path/to/templates'))
env.globals['clever_function'] = clever_function
from jinja2 import Template
def custom_function(a):
return a.replace('o', 'ay')
template = Template('Hey, my name is {{ custom_function(first_name) }} {{ func2(last_name) }}')
template.globals['custom_function'] = custom_function
Matroskin의 답변에 따라 필드에 함수를 지정할 수도 있습니다.
fields = {'first_name': 'Jo', 'last_name': 'Ko', 'func2': custom_function}
print template.render(**fields)
Will 출력:
Hey, my name is Jay Kay
Jinja2 버전 2.7.3과 함께 작동합니다.
그리고 당신이 장식가가 기능을 쉽게 정의하기를 원한다면.template.globals
브루노 브로노스키의 대답을 확인해 보세요.
@AJP의 답변이 마음에 듭니다.저는 많은 기능이 생길 때까지 그것을 말 그대로 사용했습니다.그리고 나서 저는 파이썬 기능 장식기로 바꿨습니다.
from jinja2 import Template
template = '''
Hi, my name is {{ custom_function1(first_name) }}
My name is {{ custom_function2(first_name) }}
My name is {{ custom_function3(first_name) }}
'''
jinga_html_template = Template(template)
def template_function(func):
jinga_html_template.globals[func.__name__] = func
return func
@template_function
def custom_function1(a):
return a.replace('o', 'ay')
@template_function
def custom_function2(a):
return a.replace('o', 'ill')
@template_function
def custom_function3(a):
return 'Slim Shady'
fields = {'first_name': 'Jo'}
print(jinga_html_template.render(**fields))
함수에 다음이 있는 것이 좋습니다.__name__
!
공식 문서나 스택 오버플로에서 그렇게 간단한 방법을 본 적이 없지만, 저는 이것을 발견했을 때 놀랐습니다.
# jinja2.__version__ == 2.8
from jinja2 import Template
def calcName(n, i):
return ' '.join([n] * i)
template = Template("Hello {{ calcName('Gandalf', 2) }}")
template.render(calcName=calcName)
# or
template.render({'calcName': calcName})
훨씬 더 간단한 결정이 있습니다.
@app.route('/x')
def x():
return render_template('test.html', foo=y)
def y(text):
return text
그런 다음 test.html에서:
{{ foo('hi') }}
Jinja2에서 파이썬 함수를 호출하기 위해, 당신은 유사하게 작동하는 사용자 정의 필터를 사용할 수 있습니다.globals
.
그것은 꽤 간단하고 유용합니다.내 템플릿 파일에 있습니다.txt, 나는 다음과 같이 썼습니다.
{{ data | pythonFct }}
그리고 파이썬 스크립트로:
import jinja2
def pythonFct(data):
return "This is my data: {0}".format(data)
input="my custom filter works!"
loader = jinja2.FileSystemLoader(path or './')
env = jinja2.Environment(loader=loader)
env.filters['pythonFct'] = pythonFct
result = env.get_template("myTemplate.txt").render(data=input)
print(result)
람다를 사용하여 템플릿을 주 코드에 연결합니다.
return render_template("clever_template", clever_function=lambda x: clever_function x)
그러면 템플릿의 함수를 원활하게 호출할 수 있습니다.
{{clever_function(value)}}
python 함수의 전체 세트를 가져와서 jinja2에서 액세스할 수 있는 방법이 있습니까?
네, 있습니다. 위의 다른 답변 외에도, 이것은 저에게 효과가 있습니다.
클래스를 만들고 관련 메서드로 채웁니다. 예:
class Test_jinja_object:
def __init__(self):
self.myvar = 'sample_var'
def clever_function (self):
return 'hello'
그런 다음 보기 함수에 클래스의 인스턴스를 만들고 결과 개체를 render_template 함수의 매개 변수로 템플릿에 전달합니다.
my_obj = Test_jinja_object()
이제 당신의 템플릿에서, 당신은 수업 방법을 진자로 그렇게 부를 수 있습니다.
{{ my_obj.clever_function () }}
모든 내장 기능을 가져오려면 다음을 사용합니다.
app.jinja_env.globals.update(__builtins__)
더하다.__dict__
나고끝 __builtins__
이게 안 되면요
John 32323의 답변에 근거합니다.
@John32323의 대답은 매우 깨끗한 해결책입니다.
여기에도 같은 것이 있지만, 별도의 파일에 저장하면 더 깨끗해질 수 있습니다.
도우미 파일 만들기
app\facebook.파이의
from app import app
def clever_function_1():
return u'HELLO'
def clever_function_2(a, b):
return a + b
app.jinja_env.globals.update(
clever_function_1=clever_function_1,
clever_function_2=clever_function_2,
)
앱에서 가져오기
app.py
from app import routes
from app import helper # add this one
이렇게 사용
app\some.smet
{{ clever_function_1() }}
{{ clever_function_2(a, b) }}
FastApi를을 FastApi에 .__init__.py
:
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory="templates")
def clever_function():
return u'HELLO'
templates.env.globals.update(clever_function=clever_function)
템플릿에서 다음과 같이 호출합니다.{{ clever_function() }}
Django를 사용하여 이 작업을 수행하는 경우 다음과 같은 컨텍스트를 사용하여 함수를 전달할 수 있습니다.
context = {
'title':'My title',
'str': str,
}
...
return render(request, 'index.html', context)
은 이사할수있다니를 할 수 .str
jinja2 함수
Creating a global function without passing to the template
@app.template_global('double')
def double(n):
return 2 * n
Jinja Usage`enter code here`
{{double(77)}}
Or
Creating a filter in jinja.
@app.template_filter('geo_stuff')
def hellome(a,b='dadadd'):
d=a+'it is jerry'
return d
jinja use
{{'foo'|geo_stuff}}
언급URL : https://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2
'programing' 카테고리의 다른 글
0으로 나누기 0을 반환하는 방법 (0) | 2023.06.13 |
---|---|
Oracle - 두 DateTime 열 간의 차이를 분 단위로 파악하는 데 가장 적합한 SELECT 문은 무엇입니까? (0) | 2023.06.13 |
Vue 2.7과 함께 Vue 4 사용 (0) | 2023.06.13 |
Python의 "in" 집합 연산자 (0) | 2023.06.13 |
하위 목록(범주 또는 페이지)이 있는 사용자 정의 빵 조각 (0) | 2023.06.13 |