Enviar pesquisa
Carregar
Python Templating Engine - Intro to Jinja
•
3 gostaram
•
1,250 visualizações
Eueung Mulyana
Seguir
Python CodeLabs - Python - Introduction to Jinja2 http://eueung.github.io/python/jinja2
Leia menos
Leia mais
Internet
Denunciar
Compartilhar
Denunciar
Compartilhar
1 de 27
Baixar agora
Baixar para ler offline
Recomendados
Cocos2d-x(JS) ハンズオン #12「Cocos2d-xとSpine」
Cocos2d-x(JS) ハンズオン #12「Cocos2d-xとSpine」
Tomoaki Shimizu
Intro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask Meetup
Alan Hamlett
Pester & PSScriptAnalyser - Power Test your PowerShell with PowerShell - Futu...
Pester & PSScriptAnalyser - Power Test your PowerShell with PowerShell - Futu...
DevOpsGroup
Selenium Maven With Eclipse | Edureka
Selenium Maven With Eclipse | Edureka
Edureka!
賣 K8s 的人不敢告訴你的事 (Secrets that K8s vendors won't tell you)
賣 K8s 的人不敢告訴你的事 (Secrets that K8s vendors won't tell you)
William Yeh
超簡単!!なTestLinkの使い方
超簡単!!なTestLinkの使い方
Cake YOSHIDA
Sed Introduction
Sed Introduction
Anthony Magee
Selenium WebDriver avec Java
Selenium WebDriver avec Java
Ahmed HARRAK
Recomendados
Cocos2d-x(JS) ハンズオン #12「Cocos2d-xとSpine」
Cocos2d-x(JS) ハンズオン #12「Cocos2d-xとSpine」
Tomoaki Shimizu
Intro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask Meetup
Alan Hamlett
Pester & PSScriptAnalyser - Power Test your PowerShell with PowerShell - Futu...
Pester & PSScriptAnalyser - Power Test your PowerShell with PowerShell - Futu...
DevOpsGroup
Selenium Maven With Eclipse | Edureka
Selenium Maven With Eclipse | Edureka
Edureka!
賣 K8s 的人不敢告訴你的事 (Secrets that K8s vendors won't tell you)
賣 K8s 的人不敢告訴你的事 (Secrets that K8s vendors won't tell you)
William Yeh
超簡単!!なTestLinkの使い方
超簡単!!なTestLinkの使い方
Cake YOSHIDA
Sed Introduction
Sed Introduction
Anthony Magee
Selenium WebDriver avec Java
Selenium WebDriver avec Java
Ahmed HARRAK
Jenkins
Jenkins
Lhouceine OUHAMZA
한컴MDS_AUTOSAR 기반 MBD 개발 프로세스
한컴MDS_AUTOSAR 기반 MBD 개발 프로세스
HANCOM MDS
Ansible presentation
Ansible presentation
John Lynch
Learn About the FACE Standard for Avionics Software and a Ready-to-Go COTS Pl...
Learn About the FACE Standard for Avionics Software and a Ready-to-Go COTS Pl...
Real-Time Innovations (RTI)
Jenkins with Docker
Jenkins with Docker
Yahoo!デベロッパーネットワーク
Les Streams de Java 8
Les Streams de Java 8
Antoine Rey
selenium with python training
selenium with python training
SaiprasadVella
Alphorm.com Formation KVM
Alphorm.com Formation KVM
Alphorm
Groovyで楽にSQLを実行してみよう
Groovyで楽にSQLを実行してみよう
Akira Shimosako
셸 스크립트를 이용한 클라우드 시스템 운영
셸 스크립트를 이용한 클라우드 시스템 운영
Nalee Jang
An Introduction to Test Driven Development
An Introduction to Test Driven Development
CodeOps Technologies LLP
徳丸本ができるまで
徳丸本ができるまで
Hiroshi Tokumaru
TDD (Test-driven development, 測試驅動開發) 基本教學
TDD (Test-driven development, 測試驅動開發) 基本教學
潘 冠辰
Rest api 테스트 수행가이드
Rest api 테스트 수행가이드
SangIn Choung
Code Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCo
Evgeny Mandrikov
Test unitaires
Test unitaires
Mohamed Akrouh
General introduction to intellij idea
General introduction to intellij idea
Yusup
Exception handling
Exception handling
Ravi Sharda
Test driven development
Test driven development
Nascenia IT
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Thomas Weller
Django
Django
Qing Feng
Django tutorial 2009
Django tutorial 2009
Ferenc Szalai
Mais conteúdo relacionado
Mais procurados
Jenkins
Jenkins
Lhouceine OUHAMZA
한컴MDS_AUTOSAR 기반 MBD 개발 프로세스
한컴MDS_AUTOSAR 기반 MBD 개발 프로세스
HANCOM MDS
Ansible presentation
Ansible presentation
John Lynch
Learn About the FACE Standard for Avionics Software and a Ready-to-Go COTS Pl...
Learn About the FACE Standard for Avionics Software and a Ready-to-Go COTS Pl...
Real-Time Innovations (RTI)
Jenkins with Docker
Jenkins with Docker
Yahoo!デベロッパーネットワーク
Les Streams de Java 8
Les Streams de Java 8
Antoine Rey
selenium with python training
selenium with python training
SaiprasadVella
Alphorm.com Formation KVM
Alphorm.com Formation KVM
Alphorm
Groovyで楽にSQLを実行してみよう
Groovyで楽にSQLを実行してみよう
Akira Shimosako
셸 스크립트를 이용한 클라우드 시스템 운영
셸 스크립트를 이용한 클라우드 시스템 운영
Nalee Jang
An Introduction to Test Driven Development
An Introduction to Test Driven Development
CodeOps Technologies LLP
徳丸本ができるまで
徳丸本ができるまで
Hiroshi Tokumaru
TDD (Test-driven development, 測試驅動開發) 基本教學
TDD (Test-driven development, 測試驅動開發) 基本教學
潘 冠辰
Rest api 테스트 수행가이드
Rest api 테스트 수행가이드
SangIn Choung
Code Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCo
Evgeny Mandrikov
Test unitaires
Test unitaires
Mohamed Akrouh
General introduction to intellij idea
General introduction to intellij idea
Yusup
Exception handling
Exception handling
Ravi Sharda
Test driven development
Test driven development
Nascenia IT
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Thomas Weller
Mais procurados
(20)
Jenkins
Jenkins
한컴MDS_AUTOSAR 기반 MBD 개발 프로세스
한컴MDS_AUTOSAR 기반 MBD 개발 프로세스
Ansible presentation
Ansible presentation
Learn About the FACE Standard for Avionics Software and a Ready-to-Go COTS Pl...
Learn About the FACE Standard for Avionics Software and a Ready-to-Go COTS Pl...
Jenkins with Docker
Jenkins with Docker
Les Streams de Java 8
Les Streams de Java 8
selenium with python training
selenium with python training
Alphorm.com Formation KVM
Alphorm.com Formation KVM
Groovyで楽にSQLを実行してみよう
Groovyで楽にSQLを実行してみよう
셸 스크립트를 이용한 클라우드 시스템 운영
셸 스크립트를 이용한 클라우드 시스템 운영
An Introduction to Test Driven Development
An Introduction to Test Driven Development
徳丸本ができるまで
徳丸本ができるまで
TDD (Test-driven development, 測試驅動開發) 基本教學
TDD (Test-driven development, 測試驅動開發) 基本教學
Rest api 테스트 수행가이드
Rest api 테스트 수행가이드
Code Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCo
Test unitaires
Test unitaires
General introduction to intellij idea
General introduction to intellij idea
Exception handling
Exception handling
Test driven development
Test driven development
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Semelhante a Python Templating Engine - Intro to Jinja
Django
Django
Qing Feng
Django tutorial 2009
Django tutorial 2009
Ferenc Szalai
C++ Template
C++ Template
Saket Pathak
スゴイ django - Python&Djangoで始めるWeb開発 in 札幌 #1
スゴイ django - Python&Djangoで始めるWeb開発 in 札幌 #1
makoto tsuyuki
DJ-02-Model-Single.pptx
DJ-02-Model-Single.pptx
joeveller
Finding Clojure
Finding Clojure
Matthew McCullough
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
Igor Sobreira
Learning django step 1
Learning django step 1
永昇 陳
令和から本気出す
令和から本気出す
Takashi Kitano
PrimeNG - Components para la Vida Real
PrimeNG - Components para la Vida Real
cagataycivici
Django web framework
Django web framework
Abdenour Bouateli
Discovering Django - zekeLabs
Discovering Django - zekeLabs
zekeLabs Technologies
The Ring programming language version 1.9 book - Part 52 of 210
The Ring programming language version 1.9 book - Part 52 of 210
Mahmoud Samir Fayed
Twig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHP
Fabien Potencier
The Ring programming language version 1.5.2 book - Part 43 of 181
The Ring programming language version 1.5.2 book - Part 43 of 181
Mahmoud Samir Fayed
Mico: A monkey in the cloud
Mico: A monkey in the cloud
Andrés J. Díaz
Vaadin Components @ Angular U
Vaadin Components @ Angular U
Joonas Lehtinen
Twig Brief, Tips&Tricks
Twig Brief, Tips&Tricks
Andrei Burian
Odoo Experience 2018 - From a Web Controller to a Full CMS
Odoo Experience 2018 - From a Web Controller to a Full CMS
ElínAnna Jónasdóttir
Add an interactive command line to your C++ application
Add an interactive command line to your C++ application
Daniele Pallastrelli
Semelhante a Python Templating Engine - Intro to Jinja
(20)
Django
Django
Django tutorial 2009
Django tutorial 2009
C++ Template
C++ Template
スゴイ django - Python&Djangoで始めるWeb開発 in 札幌 #1
スゴイ django - Python&Djangoで始めるWeb開発 in 札幌 #1
DJ-02-Model-Single.pptx
DJ-02-Model-Single.pptx
Finding Clojure
Finding Clojure
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
Learning django step 1
Learning django step 1
令和から本気出す
令和から本気出す
PrimeNG - Components para la Vida Real
PrimeNG - Components para la Vida Real
Django web framework
Django web framework
Discovering Django - zekeLabs
Discovering Django - zekeLabs
The Ring programming language version 1.9 book - Part 52 of 210
The Ring programming language version 1.9 book - Part 52 of 210
Twig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHP
The Ring programming language version 1.5.2 book - Part 43 of 181
The Ring programming language version 1.5.2 book - Part 43 of 181
Mico: A monkey in the cloud
Mico: A monkey in the cloud
Vaadin Components @ Angular U
Vaadin Components @ Angular U
Twig Brief, Tips&Tricks
Twig Brief, Tips&Tricks
Odoo Experience 2018 - From a Web Controller to a Full CMS
Odoo Experience 2018 - From a Web Controller to a Full CMS
Add an interactive command line to your C++ application
Add an interactive command line to your C++ application
Mais de Eueung Mulyana
FGD Big Data
FGD Big Data
Eueung Mulyana
Hyper-Connectivity and Data Proliferation - Ecosystem Perspective
Hyper-Connectivity and Data Proliferation - Ecosystem Perspective
Eueung Mulyana
Industry 4.0 And Beyond The A.I* For Surviving A Tech-Accelerated World
Industry 4.0 And Beyond The A.I* For Surviving A Tech-Accelerated World
Eueung Mulyana
Blockchain Introduction
Blockchain Introduction
Eueung Mulyana
Bringing Automation to the Classroom: A ChatOps-Based Approach
Bringing Automation to the Classroom: A ChatOps-Based Approach
Eueung Mulyana
FinTech & Cryptocurrency Introduction
FinTech & Cryptocurrency Introduction
Eueung Mulyana
Open Source Networking Overview
Open Source Networking Overview
Eueung Mulyana
ONOS SDN Controller - Clustering Tests & Experiments
ONOS SDN Controller - Clustering Tests & Experiments
Eueung Mulyana
Open stack pike-devstack-tutorial
Open stack pike-devstack-tutorial
Eueung Mulyana
Basic onos-tutorial
Basic onos-tutorial
Eueung Mulyana
ONOS SDN Controller - Introduction
ONOS SDN Controller - Introduction
Eueung Mulyana
OpenDaylight SDN Controller - Introduction
OpenDaylight SDN Controller - Introduction
Eueung Mulyana
Mininet Basics
Mininet Basics
Eueung Mulyana
Android Programming Basics
Android Programming Basics
Eueung Mulyana
Cloud Computing: Overview and Examples
Cloud Computing: Overview and Examples
Eueung Mulyana
selected input/output - sensors and actuators
selected input/output - sensors and actuators
Eueung Mulyana
Connected Things, IoT and 5G
Connected Things, IoT and 5G
Eueung Mulyana
Connectivity for Local Sensors and Actuators Using nRF24L01+
Connectivity for Local Sensors and Actuators Using nRF24L01+
Eueung Mulyana
NodeMCU with Blynk and Firebase
NodeMCU with Blynk and Firebase
Eueung Mulyana
Trends and Enablers - Connected Services and Cloud Computing
Trends and Enablers - Connected Services and Cloud Computing
Eueung Mulyana
Mais de Eueung Mulyana
(20)
FGD Big Data
FGD Big Data
Hyper-Connectivity and Data Proliferation - Ecosystem Perspective
Hyper-Connectivity and Data Proliferation - Ecosystem Perspective
Industry 4.0 And Beyond The A.I* For Surviving A Tech-Accelerated World
Industry 4.0 And Beyond The A.I* For Surviving A Tech-Accelerated World
Blockchain Introduction
Blockchain Introduction
Bringing Automation to the Classroom: A ChatOps-Based Approach
Bringing Automation to the Classroom: A ChatOps-Based Approach
FinTech & Cryptocurrency Introduction
FinTech & Cryptocurrency Introduction
Open Source Networking Overview
Open Source Networking Overview
ONOS SDN Controller - Clustering Tests & Experiments
ONOS SDN Controller - Clustering Tests & Experiments
Open stack pike-devstack-tutorial
Open stack pike-devstack-tutorial
Basic onos-tutorial
Basic onos-tutorial
ONOS SDN Controller - Introduction
ONOS SDN Controller - Introduction
OpenDaylight SDN Controller - Introduction
OpenDaylight SDN Controller - Introduction
Mininet Basics
Mininet Basics
Android Programming Basics
Android Programming Basics
Cloud Computing: Overview and Examples
Cloud Computing: Overview and Examples
selected input/output - sensors and actuators
selected input/output - sensors and actuators
Connected Things, IoT and 5G
Connected Things, IoT and 5G
Connectivity for Local Sensors and Actuators Using nRF24L01+
Connectivity for Local Sensors and Actuators Using nRF24L01+
NodeMCU with Blynk and Firebase
NodeMCU with Blynk and Firebase
Trends and Enablers - Connected Services and Cloud Computing
Trends and Enablers - Connected Services and Cloud Computing
Último
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Digicorns Technologies
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Priya Reddy
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
ydyuyu
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
meghakumariji156
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
kumargunjan9515
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
F
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Monica Sydney
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
meghakumariji156
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
kajalverma014
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理
F
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
pxcywzqs
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
meghakumariji156
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
Matthew Sinclair
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
rahman018755
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Monica Sydney
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
HenryBriggs2
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
ydyuyu
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
Matthew Sinclair
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
Matthew Sinclair
Último
(20)
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
Python Templating Engine - Intro to Jinja
1.
Python - Jinja2 Eueung
Mulyana http://eueung.github.io/python/jinja2 Python CodeLabs | Attribution-ShareAlike CC BY-SA 1 / 27
2.
Agenda Jinja Basics Rendering to
Files Jinja + Flask 2 / 27
3.
Jinja Basics 3
/ 27
4.
Example #1/1-2 HelloJohnDoe! Myfavoritenumbers:123456789 fromjinja2importTemplate template=Template('Hello{{name}}!') printtemplate.render(name='JohnDoe') t=Template("Myfavoritenumbers:{%forninrange(1,10)%}{{n}}" printt.render() <title></title> <ul> <li><ahref="abc@gmail.com">abc</a></li> <li><ahref="123@gmail.com">123</a></li> </ul> fromjinja2importTemplate template=Template(''' <title>{%blocktitle%}{%endblock%}</title> <ul> {%foruserinusers-%} <li><ahref="{{user.url}}">{{user.username}}</a></li> {%endfor-%} </ul>''') printtemplate.render(title='titlestring',users=[{'username' 4 /
27
5.
Example #1/3 <html><head><title>HelloTitle</title></head> <body>Hello.</body> </html> fromjinja2importEnvironment HTML=""" <html><head><title>{{title}}</title></head> <body>Hello.</body> </html> """ defprint_html(): printEnvironment().from_string(HTML).render(title='Hello print_html() 5 /
27
6.
Example #2/1 <html> <head> <title>{{title}}</title> </head> <body> Hello. </body> </html> basic-1.html fromjinja2importEnvironment,FileSystemLoader THIS_DIR='templates' defprint_html(): j2_env=Environment(loader=FileSystemLoader(THIS_DIR),trim_blocks= printj2_env.get_template('basic-1.html').render( title='HelloTitle' ) print_html() <html> <head> <title>HelloTitle</title> </head> <body> Hello. </body> </html> 6 /
27
7.
Example #2/2 importjinja2 templateLoader=jinja2.FileSystemLoader(searchpath="templates" templateEnv=jinja2.Environment(loader=templateLoader) TEMPLATE_FILE="basic-2.html" template=templateEnv.get_template(TEMPLATE_FILE) FAVORITES=["chocolates","lunareclipses","rabbits"] templateVars={"title":"TestExample", "description":"Asimpleinquiryoffunction." "favorites":FAVORITES} printtemplate.render(templateVars) <!doctypehtml> <htmllang="en"> <head> <metacharset="UTF-8"/> <title>{{title}}</title> <metaname="description"content="{{description}}"/> </head> <body> <divid="content"> <p>MyFavoriteThings:</p> <ul> {%foriteminfavorites-%} <li>{{item}}</li> {%endfor-%} </ul> </div> </body> </html> basic-2.html 7 /
27
8.
Example #2/2 <!doctypehtml> <htmllang="en"> <head> <metacharset="UTF-8"/> <title>TestExample</title> <metaname="description"content="Asimpleinquiryoffunction." </head> <body> <divid="content"> <p>MyFavoriteThings:</p> <ul> <li>chocolates</li> <li>lunareclipses</li> <li>rabbits</li> </ul> </div> </body> </html> 8 /
27
9.
Example #2/3 basic-3.html <!DOCTYPEhtml> <html> <head> <metacharset="utf-8"/> <title>TestJinja2</title> </head> <body> <center> <h1>HelloJinja2</h1> <p>BuiltinFilters-{{urls|length}}links</p> </center> <olalign="left"> {%setcounter=0-%} {%forurlinurls-%} {%setcounter=counter+1-%} <li><ahref="{{url}}">{{url}}</a>|counterinside:{{counter}} {%endfor-%} </ol> <p>counteroutside:{{counter}}</p> </body> </html> importos fromjinja2importEnvironment,FileSystemLoader PATH='.' TEMPLATE_ENVIRONMENT=Environment( autoescape=False, loader=FileSystemLoader(os.path.join(PATH,'templates')), trim_blocks=False) defrender_template(template_filename,context): returnTEMPLATE_ENVIRONMENT.get_template(template_filename defcreate_index_html(): fname="results/output-basic-3.html" urls=['http://example.com/1','http://example.com/2', context={ 'urls':urls } withopen(fname,'w')asf: html=render_template('basic-3.html',context) f.write(html) create_index_html() 9 /
27
10.
output-basic-3.html 10 / 27
11.
Rendering to
Files Based on the Codes by @mjhea0 (Michael Herman/Real Python) 11 / 27
12.
importos fromjinja2importEnvironment,FileSystemLoader PATH='.' TEMPLATE_ENVIRONMENT=Environment( autoescape=False, loader=FileSystemLoader(os.path.join(PATH,'templates')), trim_blocks=False) defrender_template(template_filename,context): returnTEMPLATE_ENVIRONMENT.get_template(template_filename).render(context) defcreate_index_html(): fname="results/output-t-0.html" my_string="Hello!" my_list=[0,1,2,3,4,5] context={ 'title':'titlet-0', 'my_string':my_string, 'my_list':my_list } withopen(fname,'w')asf: html=render_template('t-0.html',context) f.write(html) create_index_html() Example t-0 <divclass="container"> <p>Mystring:{{my_string}}</p> <p>Valuefromthelist:{{my_list[3]}}</p> <p>Loopthroughthelist:</p> <ul> {%forninmy_list%} <li>{{n}}</li> {%endfor%} </ul> </div> t-0.html (partial) 12
/ 27
13.
output-t-0.html 13 / 27
14.
Example t-1 {%extends"t-layout-1.html"%} {%blockcontent%} <h3>Thisisthestartofmychildtemplate</h3> <br> <p>Mystring:{{my_string}}</p> <p>Valuefromthelist:{{my_list[3]}}</p> <p>Loopthroughthelist:</p> <ul> {%forninmy_list%} <li>{{n}}</li> {%endfor%} </ul> <h3>Thisistheendofmychildtemplate</h3> {%endblock%} t-1.html <divclass="container"> <h2>Thisispartofmybasetemplate</h2> <br> {%blockcontent%}{%endblock%} <br> <h2>Thisispartofmybasetemplate</h2> </div> t-layout-1.html (partial) 14
/ 27
15.
output-t-1.html 15 / 27
16.
Example t-2 {%extends"t-layout-2.html"%} {%blockpage%}Home{%endblock%} {%blockheading%} {{super()}} {%endblock%} {%blockcontent%} <h3>Thisisthestartofmychildtemplate</h3> <br> <p>Mystring:{{my_string}}</p> <p>Valuefromthelist:{{my_list[3]}}</p> <p>Loopthroughthelist:</p> <ul> {%forninmy_list%} <li>{{n}}</li> {%endfor%} </ul> <h3>Thisistheendofmychildtemplate</h3> {%endblock%} t-2.html t-layout-2.html (partial) <divclass="container"> {%blockheading%} <h1>{%blockpage%}{%endblock%}-FlaskSuperExample {%endblock%} <h2>Thisispartofmybasetemplate</h2> <br> {%blockcontent%}{%endblock%} <br> <h2>Thisispartofmybasetemplate</h2> </div> 16
/ 27
17.
output-t-2.html 17 / 27
18.
Example t-3 t-3.html {%extends"t-layout-3.html"%} {%blocktitle%}{{title}}{%endblock%} {%blockhead%} {{super()}} {%endblock%} {%blockpage%}{{title}}{%endblock%} {%blockheading%}{{super()}}{%endblock%} {%blockcontent%} <h3>Thisisthestartofmychildtemplate</h3><br><br> <p>Mystring:{{my_string}}</p> <p>Valuefromthelist:{{my_list[3]}}</p> <p>Loopthroughthelist:</p> <ul>{%forninmy_list%} <li>{{n}}</li> {%endfor%}</ul> <br><p>Samelistwithafilter:{{my_list|join(',')}}</ <h3>Thisistheendofmychildtemplate</h3> {%blocktrailer%}{{super()}}{%endblock%} {%endblock%} t-layout-3.html (partial) <divclass="container"> {%blockheading%} <h1>{%blockpage%}{%endblock%}-FlaskSuperExample {%endblock%} <h2>Thisispartofmybasetemplate</h2> <br> {%blockcontent%}{%endblock%} <br> <h2>Thisispartofmybasetemplate</h2> <br> <divclass="trailer"> {%blocktrailer%} Watch!Thiswillbeaddedtomybaseandchildtemplates <br><br><br> {%endblock%} </div> 18
/ 27
19.
Example t-3 {%macronav_link(endpoint,name)%} <li><ahref="#{{endpoint}}">{{name}}</a></li> {%endmacro%} t-macro-3.html t-layout-3.html (partial) {%from"t-macro-3.html"importnav_linkwithcontext%} <!DOCTYPEhtml> ... {%blockhead%} <title>{%blocktitle%}{%endblock%}-FlaskSuperExample {%endblock%} ... <divid="navbar"class="collapsenavbar-collapse"> <ulclass="navnavbar-nav"> {{nav_link('home','Home')}} {{nav_link('about','About')}} {{nav_link('contact','ContactUs')}} <liclass="dropdown"> ...</li> </ul> </div> 19
/ 27
20.
output-t-3.html 20 / 27
21.
Jinja +
Flask 21 / 27
22.
fromflaskimportFlask,render_template importdatetime app=Flask(__name__) #--------------------------------------------- @app.template_filter() defdatetimefilter(value,format='%Y/%m/%d%H:%M'): returnvalue.strftime(format) app.jinja_env.filters['datetimefilter']=datetimefilter #--------------------------------------------- @app.route("/") deftemplate_test(): returnrender_template('f-template.html',my_string="Wheeeee!" @app.route("/home") defhome(): returnrender_template('f-template.html',my_string="Foo" @app.route("/about") defabout(): returnrender_template('f-template.html',my_string="Bar" @app.route("/contact") defcontact(): returnrender_template('f-template.html',my_string="FooBar" #--------------------------------------------- if__name__=='__main__': app.run(host='0.0.0.0',debug=True) Example #4 f-macro.html {%macronav_link(endpoint,name)%} {%ifrequest.endpoint.endswith(endpoint)%} <liclass="active"><ahref="{{url_for(endpoint)}}">{{name} {%else%} <li><ahref="{{url_for(endpoint)}}">{{name}}</a></li> {%endif%} {%endmacro%} 22 /
27
23.
Example #4 f-template.html {%extends"f-layout.html"%} {%blocktitle%}{{title}}{%endblock%} {%blockhead%}{{super()}}{%endblock%} {%blockpage%}{{title}}{%endblock%} {%blockheading%}{{super()}}{%endblock%} {%blockcontent%} <h3>Thisisthestartofmychildtemplate</h3> <br> <h4>Currentdate/time:{{current_time|datetimefilter}} <br> <p>Mystring:{{my_string}}</p> <p>Valuefromthelist:{{my_list[3]}}</p> <p>Loopthroughthelist:</p> <ul> {%forninmy_list%} <li>{{n}}</li> {%endfor%} </ul> <br> <p>Samelistwithafilter:{{my_list|join(',')}}</p> <h3>Thisistheendofmychildtemplate</h3> {%blocktrailer%}{{super()}}{%endblock%} {%endblock%} 23 /
27
24.
http://localhost:5000 24 / 27
25.
http://localhost:5000/about 25 / 27
26.
References 1. Welcome to
Jinja2 — Jinja2 Documentation 2. Introduction 3. Tips and Tricks 4. Template Designer 5. Primer on Jinja Templating - Real Python Other Readings 1. Jinja2 Example | Python Adventures 2. Jinja2 Examples 3. Quickstart Guide to Using Jinja2 26 / 27
27.
END Eueung Mulyana http://eueung.github.io/python/jinja2 Python CodeLabs
| Attribution-ShareAlike CC BY-SA 27 / 27
Baixar agora