Program Tip

jinja2 출력을 브라우저 대신 Python으로 파일로 렌더링하는 방법

programtip 2020. 11. 10. 22:12
반응형

jinja2 출력을 브라우저 대신 Python으로 파일로 렌더링하는 방법


렌더링하려는 jinja2 템플릿 (.html 파일)이 있습니다 (토큰을 내 py 파일의 값으로 대체). 그러나 렌더링 된 결과를 브라우저에 보내는 대신 새 .html 파일에 쓰고 싶습니다. 솔루션이 장고 템플릿과 비슷할 것이라고 상상합니다.

어떻게 할 수 있습니까?


이런 건 어때?

from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('test.html')
output_from_parsed_template = template.render(foo='Hello World!')
print(output_from_parsed_template)

# to save the results
with open("my_new_file.html", "w") as fh:
    fh.write(output_from_parsed_template)

test.html

<h1>{{ foo }}</h1>

산출

<h1>Hello World!</h1>

Flask와 같은 프레임 워크를 사용하는 경우 돌아 가기 전에보기 하단에서이 작업을 수행 할 수 있습니다.

output_from_parsed_template = render_template('test.html', foo="Hello World!")
with open("some_new_file.html", "wb") as f:
    f.write(output_from_parsed_template)
return output_from_parsed_template

다음과 같이 템플릿 스트림을 파일로 덤프 할 수 있습니다.

Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')

참조 : http://jinja.pocoo.org/docs/dev/api/#jinja2.environment.TemplateStream.dump


따라서 템플릿을로드 한 후 render를 호출 한 다음 출력을 파일에 씁니다. 'with'문은 컨텍스트 관리자입니다. 들여 쓰기 안에는 'f'라는 객체와 같은 열린 파일이 있습니다.

template = jinja_environment.get_template('CommentCreate.html')     
output = template.render(template_values)) 

with open('my_new_html_file.html', 'w') as f:
    f.write(output)

참고 URL : https://stackoverflow.com/questions/11857530/how-do-i-render-jinja2-output-to-a-file-in-python-instead-of-a-browser

반응형