SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerymanugoel2003
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineJason Terpko
 
Closures in Javascript
Closures in JavascriptClosures in Javascript
Closures in JavascriptDavid Semeria
 
Javascript under the hood 2
Javascript under the hood 2Javascript under the hood 2
Javascript under the hood 2Thang Tran Duc
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHPNisa Soomro
 
CSS Pseudo Classes
CSS Pseudo ClassesCSS Pseudo Classes
CSS Pseudo Classesfrontendne
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flaskjuzten
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
 

Mais procurados (20)

Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation Pipeline
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Closures in Javascript
Closures in JavascriptClosures in Javascript
Closures in Javascript
 
Javascript under the hood 2
Javascript under the hood 2Javascript under the hood 2
Javascript under the hood 2
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
CSS Pseudo Classes
CSS Pseudo ClassesCSS Pseudo Classes
CSS Pseudo Classes
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flask
 
Sequelize
SequelizeSequelize
Sequelize
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 

Semelhante a 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
 
`From Prototype to Drupal` by Andrew Ivasiv
`From Prototype to Drupal` by Andrew Ivasiv`From Prototype to Drupal` by Andrew Ivasiv
`From Prototype to Drupal` by Andrew IvasivLemberg Solutions
 

Semelhante a 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
 
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
 
`From Prototype to Drupal` by Andrew Ivasiv
`From Prototype to Drupal` by Andrew Ivasiv`From Prototype to Drupal` by Andrew Ivasiv
`From Prototype to Drupal` by Andrew Ivasiv
 

Último

Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxnuruddin69
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...HenryBriggs2
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfsmsksolar
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwaitjaanualu31
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 

Último (20)

Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 

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