렌더링 할 jinja2 템플릿 (.html 파일)이 있습니다 (내 py 파일의 값으로 토큰을 바꿉니다). 그러나 브라우저에 렌더링 된 결과를 보내는 대신 새 .html 파일에 작성하고 싶습니다. 나는 그 솔루션이 또한 장고 템플릿과 비슷할 것이라고 생각한다.jinja2 출력을 브라우저 대신 Python으로 파일로 렌더링하는 방법
어떻게하면됩니까?
렌더링 할 jinja2 템플릿 (.html 파일)이 있습니다 (내 py 파일의 값으로 토큰을 바꿉니다). 그러나 브라우저에 렌더링 된 결과를 보내는 대신 새 .html 파일에 작성하고 싶습니다. 나는 그 솔루션이 또한 장고 템플릿과 비슷할 것이라고 생각한다.jinja2 출력을 브라우저 대신 Python으로 파일로 렌더링하는 방법
어떻게하면됩니까?
어때?
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", "wb") as fh:
fh.write(output_from_parsed_template)
test.html를
<h1>{{ foo }}</h1>
출력
<h1>Hello World!</h1>
이 같은 플라스크와 같은 프레임 워크를 사용하는 다음의 하단에이 작업을 수행 할 수있는 경우 돌아 오기 전에보기.
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
훨씬 더 좋은 답변 :-) – aychedee
빠른 응답을 해주셔서 감사합니다. 내가 제대로 이해하고 있다면, 첫 번째 SNIPPIT에 : jinja2 가져 오기 환경에서 , FileSystemLoader ENV = 환경 (로더 = FileSystemLoader ('템플릿')) 템플릿 = env.get_template ('인 test.html') output_from_parsed_template = template.render (foo = 'Hello World!') print output_from_parsed_template 인쇄 라인을 일종의 파일 쓰기 라인으로 대체 할 수 있습니다. 그 맞습니까? 그러한 행은 파일에 무엇을 쓸 수 있습니까? Re. 플라스크, 이것은 큰 응용 프로그램의 작은 부분입니다, 그래서 프레임 워크를 사용할 수 있을지 모르겠다. –
@BillG : 위의 편집을 참조하십시오. – sberry
그래서 템플릿을로드 한 후에 렌더링을 호출 한 다음 출력을 파일에 씁니다. '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)
그래서이 모양은 다음과 같습니다 : TEMPLATE_DIR = os.path.join (os.path.dirname (__ file__), 'templates') jinja_environment = \ jinja2.Environment (autoescape = False, loader = jinja2 .FileSystemLoader (template_dir의)) 템플릿 = jinja_environment.get_template 열기 ('my_new_html_file.html'와 ('CommentCreate.html') self.response.out.write (template.render (template_values)) , 'w') f : f.write (response.content) 여기서 template_values는 이미 채워진 곳입니다. 필요에 따라 수정하십시오. 감사. –
잠깐만, 제 대답을 조금 편집 해 드리겠습니다 ... – aychedee
설명해 주셔서 고맙습니다. 나는 이것을 마침내 시험해 볼 기회가있었습니다. 처음에는 "No such file or directory : 'my_new_file.html'"오류가 발생했습니다. 분명히 파일이 이미 존재해야합니다. 그런 다음 템플릿 파일을 복사하고 이름을 'my_new_file.html'로 변경했습니다. 이제 오류가 발생합니다 : IOError : 파일이 쓰기 위해 열리지 않습니다. Google App Engine에서 개발 중이기 때문일 수 있습니까? –
당신은 파일에 템플릿 스트림을 덤프 할 수 있습니다
Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
참조 : http://jinja.pocoo.org/docs/dev/api/#jinja2.environment.TemplateStream.dump
그것은 파이썬 방법이다! – sudoz
sberry 및 aychedee 직장에서 답변 위, 난 단지 f.close를 추가했다 (). 그렇지 않으면 디렉토리에서 파일을 찾을 수 없습니다.
일부 프레임 워크에서 jinja2를 사용하고 있습니까? 아니면 독립 실행 형입니까? – sberry