Jinjia2 template Template rendering and parameter passing
The project structure is as follows:
Main app file code:
fromFlaskImportFlask,render_templateapp= Flask (__name__) @app. Route ('/')defindex ():classPerson (object): Name='HyQ' Age= 25P=Person () context= { 'username':'HyQ', 'Gender':'male', ' Age':' -', ' Person':p,'Websites':{ 'Baidu':'www.baidu.com', 'Google':'www.google.com' } } returnRender_template ('index.html',**context)if __name__=='__main__': App.run (Debug= True)
The index.html file code is as follows:
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Title</title></Head><Body>This is the text that appears in the HTML file<P>User name: {{username}}</P> <P>Gender: {{gender}}</P> <P>Age: {{ages}}</P> <HR> <P>Name: {{Person.name}}</P> <P>Age: {{person.age}}</P> <HR> <P>Baidu: {{Websites.baidu}}</P> <P>Google: {{websites.google}}</P></Body></HTML>
# # # Flask Render Jinja2 templates and parameters:
1. How to render the template:
* The template is placed under the ' Templates ' folder
* Import the ' render_template ' function from ' flask '.
* In the view function, use the ' render_template ' function to render the template. Note: Simply fill in the name of the template and do not need to fill in the path to the ' Templates ' folder.
2. Template transfer:
* If there is only one or a few parameters, add the keyword parameter directly to the ' render_template ' function.
* If there are multiple parameters, then you can put all the parameters in the dictionary, and then in ' Render_template ',
Use two asterisks to translate the dictionary into key parameters, which makes it easier to manage and use the code.
3. In the template, if you want to use a variable, the syntax is: ' {{params}} '
4. Access a property in the model or a dictionary, either in the form of ' {{params.property}} ' or ' {{params[' age '}} '.
Front-end Display effect:
Flask Web Development Road Four