SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Flask Templates
(aka Jinja2)
by @alanhamlett
Blocks ( templates/common/base.html )
Blocks name parts of your template, and can be re-used in child templates.
<html>
<title>{% block title %}My Website{% endblock %}</title>
<body>
{% block body %}
{% endblock %}
</body>
</html>
Inheritance ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<form method="POST">
<p><input type="text" name="username" /></p>
<p><input type="password" name="password" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Variable Scope ( templates/common/base.html )
<html>
<title>{% block title %}My Website{% endblock %}</title>
<body>
{% with %}
{% set variable = "value" %}
{% block body %}
{% endblock %}
{% endwith %}
</body>
</html>
Variable Scope ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<form method="POST">
<p><input type="hidden" name="variable" value="{{variable}}" /></p>
<p><input type="text" name="username" /></p>
<p><input type="password" name="password" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Rendering Templates ( __init__.py )
from flask import Flask
app = Flask(__name__)
from flask import render_template
@app.route("/login")
def login():
return render_template('login.html')
if __name__ == "__main__":
app.run()
Rendering Templates ( __init__.py )
from flask import Flask
app = Flask(__name__)
from . import views
if __name__ == "__main__":
app.run()
Rendering Templates ( views.py )
from . import app
from flask import render_template
@app.route("/login")
def login():
context = {
'features': [
{'icon': 'free.png', 'name': 'Free'},
{'icon': 'easy.png', 'name': 'Easy'},
{'icon': 'powerful.png', 'name': 'Powerful'},
],
}
return render_template('login.html', **context)
Rendering Variables ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<h1>Included Features:</h1>
<ul>
{% for feature in features %}
<li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}" /> {{feature.name}}</li>
{% endfor %}
</ul>
<form method="POST">
<p><input type="text" name="username" /></p>
<p><input type="password" name="password" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Filters ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<h1>Included Features:</h1>
<ul>
{% for feature in features %}
<li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}"/> {{feature.name|lower}}</li>
{% endfor %}
</ul>
<form method="POST">
<p><input type="text" name="username" /></p>
<p><input type="password" name="password" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Flask-WTF ( forms.py )
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email, Length
class LoginForm(Form):
username = StringField('name', validators=[DataRequired(), Email()])
username = PasswordField('name', validators=[DataRequired(), Length(min=6)])
Flask-WTF ( views.py )
from . import app
from .forms import LoginForm
from flask import render_template, request
@app.route("/login", methods=('GET', 'POST'))
def login():
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
return redirect('/myprofile')
return render_template('login.html', form=form)
Flask-WTF ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<form method="POST">
<p>Username <input type="text" name="username" value="{{form.data.username or ''}}" /></p>
<p>Password <input type="password" name="password" value="{{form.data.password or ''}}" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Flask-WTF ( templates/login.html )
...
{% block body %}
<form method="POST">
{% for field in form._fields.values() %}
< div class="form-group" >
{{ field.label(class="col-sm-3 control-label") }}
< div class="col-sm-6 col-md-4" >
{{ field(class="form-control") }}
{% for error in field.errors %}
< p>{{error}}</ p>
{% endfor %}
</ div>
</ div>
{% endfor %}
< div class="form-group" >
< div class="col-sm-6 col-md-4 col-sm-offset-3" >
< button type="submit">Login</button>
</ div>
</ div>
</form>
{% endblock %}
...
Flask-Admin
Flask-Admin ( admin.py )
from . import app
from .models import db, User
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
admin = Admin(app)
admin.add_view(ModelView(User, db.session))
Flask-Admin ( __init__.py )
from flask import Flask
app = Flask(__name__)
from . import views
from . import admin
if __name__ == "__main__":
app.run()
Flask-Admin
Extend these Flask-Admin classes to protect your Admin pages:
● flask.ext.admin.AdminIndexView
● sqla.ModelView
Flask-Admin ( admin.py )
from . import app
from .models import db, User
from flask.ext.admin import Admin, AdminIndexView as UnsafeAdminIndexView, expose
from flask.ext.admin.contrib.sqla import ModelView
class AdminIndexView(UnsafeAdminIndexView):
@expose('/')
def index(self):
if not app.current_user.is_authenticated():
return redirect('/login')
if not app.current_user.is_admin:
abort(403)
return super(AdminIndexView, self).index()
@expose('/login/')
def login_view(self):
return redirect('/login')
@expose('/logout/')
def logout_view(self):
return redirect('/logout')
admin = Admin(app, index_view=AdminIndexView(), template_mode='bootstrap3', base_template='admin/custom_base.html')
admin.add_view(ModelView(User, db.session))
Flask-Admin ( admin.py )...
class ModelView(sqla.ModelView):
edit_template = 'admin/model/edit.html'
create_template = 'admin/model/create.html'
list_template = 'admin/model/custom_list.html'
def __init__(self, *args, **kwargs):
if 'exclude' in kwargs:
self.form_excluded_columns = kwargs['exclude']
del kwargs['exclude']
if 'include' in kwargs:
self.column_list = kwargs['include']
del kwargs['include']
pass_through = [
'can_create',
'can_edit',
'can_delete',
]
for item in pass_through:
if item in kwargs:
setattr(self, item, kwargs[item])
del kwargs[item]
super(ModelView, self).__init__(*args, **kwargs)
def is_accessible(self):
return app.current_user.is_authenticated() and app.current_user.is_admin
admin.add_view(ModelView(User, db.session, category='Users', exclude=['password', 'heartbeats'], can_delete=False))
...
Now go build something cool!
Alan Hamlett
@alanhamlett on Twitter & GitHub
alan@wakatime.com
View this online at
http://slidesha.re/1wfDzrv

Contenu connexe

Tendances

Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
OpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of SwaggerOpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of SwaggerSmartBear
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Bootstrap PPT by Mukesh
Bootstrap PPT by MukeshBootstrap PPT by Mukesh
Bootstrap PPT by MukeshMukesh Kumar
 
Internet and World Wide Web How To Program (5th Edition)
Internet and World Wide Web How To Program (5th Edition)Internet and World Wide Web How To Program (5th Edition)
Internet and World Wide Web How To Program (5th Edition)hengoofga
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flaskjuzten
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Javascript Arrow function
Javascript Arrow functionJavascript Arrow function
Javascript Arrow functiontanerochris
 
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015Innomatic Platform
 
Bootiful Development with Spring Boot and React
Bootiful Development with Spring Boot and ReactBootiful Development with Spring Boot and React
Bootiful Development with Spring Boot and ReactVMware Tanzu
 
Node.js Event Emitter
Node.js Event EmitterNode.js Event Emitter
Node.js Event EmitterEyal Vardi
 
Background property in css
Background property in cssBackground property in css
Background property in cssDhruvin Nakrani
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentationOleksii Usyk
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial之宇 趙
 

Tendances (20)

Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
OpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of SwaggerOpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of Swagger
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Bootstrap PPT by Mukesh
Bootstrap PPT by MukeshBootstrap PPT by Mukesh
Bootstrap PPT by Mukesh
 
Internet and World Wide Web How To Program (5th Edition)
Internet and World Wide Web How To Program (5th Edition)Internet and World Wide Web How To Program (5th Edition)
Internet and World Wide Web How To Program (5th Edition)
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flask
 
Flask Basics
Flask BasicsFlask Basics
Flask Basics
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Javascript Arrow function
Javascript Arrow functionJavascript Arrow function
Javascript Arrow function
 
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
Building Multi-Tenant and SaaS products in PHP - CloudConf 2015
 
Express JS
Express JSExpress JS
Express JS
 
Javascript
JavascriptJavascript
Javascript
 
Bootiful Development with Spring Boot and React
Bootiful Development with Spring Boot and ReactBootiful Development with Spring Boot and React
Bootiful Development with Spring Boot and React
 
Node.js Event Emitter
Node.js Event EmitterNode.js Event Emitter
Node.js Event Emitter
 
Background property in css
Background property in cssBackground property in css
Background property in css
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 

Similaire à Intro to Jinja2 Templates - San Francisco Flask Meetup

Jinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask MeetupJinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask MeetupAlan Hamlett
 
Django Templates
Django TemplatesDjango Templates
Django TemplatesWilly Liu
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIOliver Häger
 
How to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento ExtensionHow to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento ExtensionHendy Irawan
 
引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7makoto tsuyuki
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
Technical Preview: The New Shopware Admin
Technical Preview: The New Shopware AdminTechnical Preview: The New Shopware Admin
Technical Preview: The New Shopware AdminPhilipp Schuch
 
Understanding form helpers
Understanding form helpersUnderstanding form helpers
Understanding form helpersBruno Almeida
 
카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angular카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angularif kakao
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2RORLAB
 
Vue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówVue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówLaravel Poland MeetUp
 

Similaire à Intro to Jinja2 Templates - San Francisco Flask Meetup (20)

Jinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask MeetupJinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask Meetup
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Django Templates
Django TemplatesDjango Templates
Django Templates
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UI
 
How to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento ExtensionHow to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento Extension
 
引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7
 
iWebkit
iWebkitiWebkit
iWebkit
 
Polymer
PolymerPolymer
Polymer
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
1cst
1cst1cst
1cst
 
Technical Preview: The New Shopware Admin
Technical Preview: The New Shopware AdminTechnical Preview: The New Shopware Admin
Technical Preview: The New Shopware Admin
 
JSP
JSPJSP
JSP
 
Understanding form helpers
Understanding form helpersUnderstanding form helpers
Understanding form helpers
 
카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angular카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angular
 
Fcr 2
Fcr 2Fcr 2
Fcr 2
 
Geb qa fest2017
Geb qa fest2017Geb qa fest2017
Geb qa fest2017
 
Introduction to Html5
Introduction to Html5Introduction to Html5
Introduction to Html5
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Vue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówVue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentów
 
Bootstrap
BootstrapBootstrap
Bootstrap
 

Dernier

Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsDILIPKUMARMONDAL6
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 

Dernier (20)

Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teams
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 

Intro to Jinja2 Templates - San Francisco Flask Meetup

  • 2. Blocks ( templates/common/base.html ) Blocks name parts of your template, and can be re-used in child templates. <html> <title>{% block title %}My Website{% endblock %}</title> <body> {% block body %} {% endblock %} </body> </html>
  • 3. Inheritance ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <form method="POST"> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 4. Variable Scope ( templates/common/base.html ) <html> <title>{% block title %}My Website{% endblock %}</title> <body> {% with %} {% set variable = "value" %} {% block body %} {% endblock %} {% endwith %} </body> </html>
  • 5. Variable Scope ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <form method="POST"> <p><input type="hidden" name="variable" value="{{variable}}" /></p> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 6. Rendering Templates ( __init__.py ) from flask import Flask app = Flask(__name__) from flask import render_template @app.route("/login") def login(): return render_template('login.html') if __name__ == "__main__": app.run()
  • 7. Rendering Templates ( __init__.py ) from flask import Flask app = Flask(__name__) from . import views if __name__ == "__main__": app.run()
  • 8. Rendering Templates ( views.py ) from . import app from flask import render_template @app.route("/login") def login(): context = { 'features': [ {'icon': 'free.png', 'name': 'Free'}, {'icon': 'easy.png', 'name': 'Easy'}, {'icon': 'powerful.png', 'name': 'Powerful'}, ], } return render_template('login.html', **context)
  • 9. Rendering Variables ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <h1>Included Features:</h1> <ul> {% for feature in features %} <li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}" /> {{feature.name}}</li> {% endfor %} </ul> <form method="POST"> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 10.
  • 11. Filters ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <h1>Included Features:</h1> <ul> {% for feature in features %} <li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}"/> {{feature.name|lower}}</li> {% endfor %} </ul> <form method="POST"> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 12. Flask-WTF ( forms.py ) from flask.ext.wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email, Length class LoginForm(Form): username = StringField('name', validators=[DataRequired(), Email()]) username = PasswordField('name', validators=[DataRequired(), Length(min=6)])
  • 13. Flask-WTF ( views.py ) from . import app from .forms import LoginForm from flask import render_template, request @app.route("/login", methods=('GET', 'POST')) def login(): form = LoginForm(request.form) if request.method == 'POST' and form.validate(): return redirect('/myprofile') return render_template('login.html', form=form)
  • 14. Flask-WTF ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <form method="POST"> <p>Username <input type="text" name="username" value="{{form.data.username or ''}}" /></p> <p>Password <input type="password" name="password" value="{{form.data.password or ''}}" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 15. Flask-WTF ( templates/login.html ) ... {% block body %} <form method="POST"> {% for field in form._fields.values() %} < div class="form-group" > {{ field.label(class="col-sm-3 control-label") }} < div class="col-sm-6 col-md-4" > {{ field(class="form-control") }} {% for error in field.errors %} < p>{{error}}</ p> {% endfor %} </ div> </ div> {% endfor %} < div class="form-group" > < div class="col-sm-6 col-md-4 col-sm-offset-3" > < button type="submit">Login</button> </ div> </ div> </form> {% endblock %} ...
  • 17. Flask-Admin ( admin.py ) from . import app from .models import db, User from flask.ext.admin import Admin from flask.ext.admin.contrib.sqla import ModelView admin = Admin(app) admin.add_view(ModelView(User, db.session))
  • 18. Flask-Admin ( __init__.py ) from flask import Flask app = Flask(__name__) from . import views from . import admin if __name__ == "__main__": app.run()
  • 19. Flask-Admin Extend these Flask-Admin classes to protect your Admin pages: ● flask.ext.admin.AdminIndexView ● sqla.ModelView
  • 20. Flask-Admin ( admin.py ) from . import app from .models import db, User from flask.ext.admin import Admin, AdminIndexView as UnsafeAdminIndexView, expose from flask.ext.admin.contrib.sqla import ModelView class AdminIndexView(UnsafeAdminIndexView): @expose('/') def index(self): if not app.current_user.is_authenticated(): return redirect('/login') if not app.current_user.is_admin: abort(403) return super(AdminIndexView, self).index() @expose('/login/') def login_view(self): return redirect('/login') @expose('/logout/') def logout_view(self): return redirect('/logout') admin = Admin(app, index_view=AdminIndexView(), template_mode='bootstrap3', base_template='admin/custom_base.html') admin.add_view(ModelView(User, db.session))
  • 21. Flask-Admin ( admin.py )... class ModelView(sqla.ModelView): edit_template = 'admin/model/edit.html' create_template = 'admin/model/create.html' list_template = 'admin/model/custom_list.html' def __init__(self, *args, **kwargs): if 'exclude' in kwargs: self.form_excluded_columns = kwargs['exclude'] del kwargs['exclude'] if 'include' in kwargs: self.column_list = kwargs['include'] del kwargs['include'] pass_through = [ 'can_create', 'can_edit', 'can_delete', ] for item in pass_through: if item in kwargs: setattr(self, item, kwargs[item]) del kwargs[item] super(ModelView, self).__init__(*args, **kwargs) def is_accessible(self): return app.current_user.is_authenticated() and app.current_user.is_admin admin.add_view(ModelView(User, db.session, category='Users', exclude=['password', 'heartbeats'], can_delete=False)) ...
  • 22. Now go build something cool! Alan Hamlett @alanhamlett on Twitter & GitHub alan@wakatime.com View this online at http://slidesha.re/1wfDzrv