(window.webpackJsonp=window.webpackJsonp||[]).push([[35],{471:function(t,a,e){t.exports=e.p+"assets/img/jinja2-intro.977097d0.png"},601:function(t,a,e){"use strict";e.r(a);var s=e(56),n=Object(s.a)({},(function(){var t=this,a=t.$createElement,s=t._self._c||a;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h1",{attrs:{id:"what-is-jinja2"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#what-is-jinja2"}},[t._v("#")]),t._v(" What is Jinja2?")]),t._v(" "),s("h2",{attrs:{id:"what-is-a-template-language"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#what-is-a-template-language"}},[t._v("#")]),t._v(" What is a Template Language")]),t._v(" "),s("p",[t._v("A template is a text file. It can generate any text-based format (HTML, XML, CSV, etc). It usually contains variables, which get replaced with values when the template is evaluated, and tags, which control the logic of the template.")]),t._v(" "),s("p",[t._v("The syntax used in a template is usually known as a template language and the underlying code that evaluates the template is called a template engine.")]),t._v(" "),s("p",[t._v("For example, the Django web framework has an embedded template language called the "),s("em",[t._v("Django Template Language")]),s("sup",{staticClass:"footnote-ref"},[s("a",{attrs:{href:"#fn1",id:"fnref1"}},[t._v("[1]")])]),t._v(". Flask comes packaged with the powerful Jinja2"),s("sup",{staticClass:"footnote-ref"},[s("a",{attrs:{href:"#fn2",id:"fnref2"}},[t._v("[2]")])]),t._v(" template language.")]),t._v(" "),s("h2",{attrs:{id:"jinja2"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#jinja2"}},[t._v("#")]),t._v(" Jinja2")]),t._v(" "),s("p",[t._v('Jinja, also commonly known as "Jinja2" to specify the newest release version, is a Python template engine often used to create HTML, XML or other markup formats that are returned to the users via an HTTP response. In our case, we\'ll mostly be creating HTML files from the templates.')]),t._v(" "),s("div",{staticClass:"custom-block tip"},[s("p",{staticClass:"custom-block-title"},[t._v("TIP")]),t._v(" "),s("p",[t._v("Jinja Templates are just "),s("code",[t._v(".html")]),t._v(" files with the added Jinja code. By convention, they live in the "),s("code",[t._v("/templates")]),t._v(" directory in a Flask project.")])]),t._v(" "),s("h2",{attrs:{id:"why-use-jinja2"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#why-use-jinja2"}},[t._v("#")]),t._v(" Why Use Jinja2")]),t._v(" "),s("p",[t._v("Jinja2 is a good choice because it's popular, has simple syntax and is an independent open-source project. It can be used as an external dependency by other code libraries, and it doesn't depend on Flask.")]),t._v(" "),s("p",[t._v("Unlike the Django Template Language which is tied to the Django ecosystem, you can use Jinja2 in any of your projects as a third party library.")]),t._v(" "),s("h2",{attrs:{id:"introduction-to-jinja2-syntax"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#introduction-to-jinja2-syntax"}},[t._v("#")]),t._v(" Introduction to Jinja2 Syntax")]),t._v(" "),s("p",[t._v("Jinja2 syntax can contain variables as well as some programming logic, which when evaluated (or rendered into HTML), are replaced with actual values.")]),t._v(" "),s("p",[t._v("The variables and/or logic are placed between tags or delimiters. Jinja templates use "),s("code",[t._v("{% ... %}")]),t._v(" for expressions or logic (like "),s("code",[t._v("for")]),t._v(" loops). Double curly braces "),s("code",[t._v("{​{ ... }​}")]),t._v(" are used for outputting the results of an expression or a variable to the end user.")]),t._v(" "),s("p",[t._v("Let's take a quick look at a self-contained example. In this example, you'll use the "),s("code",[t._v("{​{ ... }​}")]),t._v(" syntax to interpolate values to a string. If you've already installed Flask in your current environment, Jinja2 should already be installed. If not, you can always install it to your current development environment via "),s("code",[t._v("pip install jinja2")]),t._v(".")]),t._v(" "),s("div",{staticClass:"language-python extra-class"},[s("pre",{pre:!0,attrs:{class:"language-python"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" jinja2 "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" Template\n\nt "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" Template"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token triple-quoted-string string"}},[t._v('"""\n\n\n

Greetings!

\n

Hello, {{ name }}!

\n\n\n"""')]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("print")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("t"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("render"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("name"),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"John Doe"')]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("This should give you the following output:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("html")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("body")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("h1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Greetings!"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Hello, John Doe!"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("In line 7 of the code snippet above, notice how we've used the "),s("code",[t._v("{​{ name }​}")]),t._v(" syntax to create a placeholder. Later, the template engine interpolates the placeholder with a value. Here the variable "),s("code",[t._v("name")]),t._v(" inside the curly braces is the placeholder and we passed a value to it in line 13.")]),t._v(" "),s("h2",{attrs:{id:"example-using-flask"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#example-using-flask"}},[t._v("#")]),t._v(" Example Using Flask")]),t._v(" "),s("p",[t._v("The above section shows how you can use Jinja2 template engine to add values dynamically to an HTML string. In this section, we'll see how you can do the same to a dedicated HTML file.")]),t._v(" "),s("p",[t._v("To follow along, create a new HTML file named "),s("code",[t._v("jinja2-intro.html")]),t._v(" in your Flask project's "),s("code",[t._v("/templates")]),t._v(" folder. Your folder structure should look something like this:")]),t._v(" "),s("div",{staticClass:"language- extra-class"},[s("pre",{pre:!0,attrs:{class:"language-text"}},[s("code",[t._v(".\n├── app.py\n└── templates\n └── jinja2-intro.html\n")])])]),s("p",[t._v("Now, add the following HTML string to the "),s("code",[t._v("/templates/jinja2-intro.html")]),t._v(" file:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- jinja2-intro.html --\x3e")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token doctype"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("html")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("body")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("h1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Hi, {{ name }}!"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("This is your introduction to {{ template_name }} template!"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("The above HTML string has two placeholders, "),s("code",[t._v("name")]),t._v(" and "),s("code",[t._v("template_name")]),t._v(". We'll push values to these placeholders from our Flask code.")]),t._v(" "),s("p",[t._v("Flask's "),s("code",[t._v("render_template")]),t._v(" method will be used to send our interpolated HTML file to the browser. This method is called "),s("em",[t._v("render_template")]),t._v(" because it evaluates the Jinja code in your HTML file, fills in the necessary placeholders and shows (renders) the content of the file to the browser.")]),t._v(" "),s("p",[t._v("For this to work, you'll have to create a new endpoint to access this newly created page from browser. Your "),s("code",[t._v("app.py")]),t._v(" should look like the following:")]),t._v(" "),s("div",{staticClass:"language-python extra-class"},[s("pre",{pre:!0,attrs:{class:"language-python"}},[s("code",[s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("# app.py")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" flask "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" Flask\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" flask "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" render_template\n\napp "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" Flask"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("__name__"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n\n"),s("span",{pre:!0,attrs:{class:"token decorator annotation punctuation"}},[t._v("@app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("route")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"/jinja2"')]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("def")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("render_jinja2_intro")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" render_template"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"jinja2-intro.html"')]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" name"),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"John Doe"')]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" template_name"),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"Jinja2"')]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("Here, we've created a new endpoint "),s("code",[t._v("/jinja2")]),t._v(". Pay attention to line 10, where we've passed the name of the HTML file "),s("code",[t._v("jinja2-intro.html")]),t._v(" as the first argument of the "),s("code",[t._v("render_template")]),t._v(" method. The other two arguments "),s("code",[t._v("name")]),t._v(" and "),s("code",[t._v("template_name")]),t._v(" pass values to the Jinja2 template engine. The "),s("code",[t._v("render_template")]),t._v(" method replaces the placeholders with actual values and renders the final HTML file into the browser.")]),t._v(" "),s("p",[t._v("Run the Flask app and go to "),s("a",{attrs:{href:"localhost:5000/jinja2"}},[t._v("localhost:5000/jinja2")]),t._v(". Your browser should show a page like this:")]),t._v(" "),s("p",[s("img",{attrs:{src:e(471),alt:"jinja2-rendering"}})]),t._v(" "),s("h2",{attrs:{id:"conclusion"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#conclusion"}},[t._v("#")]),t._v(" Conclusion")]),t._v(" "),s("p",[t._v("In this tutorial you've learned how to interpolate placeholder values in strings using the Jinja2 template language. Also, you've learned how to fill in the placeholder values inside an HTML file using Jinja2 and send it to your browser via Flask's "),s("code",[t._v("render_template")]),t._v(" method.")]),t._v(" "),s("hr",{staticClass:"footnotes-sep"}),t._v(" "),s("section",{staticClass:"footnotes"},[s("ol",{staticClass:"footnotes-list"},[s("li",{staticClass:"footnote-item",attrs:{id:"fn1"}},[s("p",[s("a",{attrs:{href:"https://docs.djangoproject.com/en/3.0/ref/templates/language/",target:"_blank",rel:"noopener noreferrer"}},[t._v("The Django Template Language"),s("OutboundLink")],1),t._v(" "),s("a",{staticClass:"footnote-backref",attrs:{href:"#fnref1"}},[t._v("↩︎")])])]),t._v(" "),s("li",{staticClass:"footnote-item",attrs:{id:"fn2"}},[s("p",[s("a",{attrs:{href:"https://jinja.palletsprojects.com/en/2.11.x/",target:"_blank",rel:"noopener noreferrer"}},[t._v("Jinja2 Official Documentation"),s("OutboundLink")],1),t._v(" "),s("a",{staticClass:"footnote-backref",attrs:{href:"#fnref2"}},[t._v("↩︎")])])])])])])}),[],!1,null,null,null);a.default=n.exports}}]);