Interview question
How do you work with templates in web frameworks? Web frameworks में templates के साथ कैसे काम करते हैं?
Answer
# Flask templates with Jinja2
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<name>')
def hello(name):
return render_template('hello.html', name=name, age=25)
# hello.html template
# <h1>Hello, {{ name }}!</h1>
# <p>Age: {{ age }}</p>
#
# {% if age >= 18 %}
# <p>You are an adult</p>
# {% else %}
# <p>You are a minor</p>
# {% endif %}
#
# {% for item in items %}
# <p>{{ item }}</p>
# {% endfor %}
# Django templates
from django.shortcuts import render
def view(request):
context = {'name': 'John', 'items': [1, 2, 3]}
return render(request, 'template.html', context)
# template.html
# <h1>Hello, {{ name }}</h1>
#
# {% for item in items %}
# <p>{{ item }}</p>
# {% endfor %}
#
# {% load static %}
# <link rel="stylesheet" href="{% static 'css/style.css' %}">
# Template inheritance
# base.html
# <!DOCTYPE html>
# <html>
# {% block content %}
# {% endblock %}
# </html>
#
# child.html
# {% extends 'base.html' %}
#
# {% block content %}
# <h1>Child content</h1>
# {% endblock %}
# FastAPI with Jinja2
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from starlette.requests import Request
app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')
templates = Jinja2Templates(directory='templates')
@app.get('/items/{id}')
async def read_item(request: Request, id: str):
return templates.TemplateResponse('item.html', {'request': request, 'id': id})Flask (Jinja2):
return render_template('template.html', var=value)
Django:
return render(request, 'template.html', context)
Template syntax:
{{ variable }}
{% for item in items %}
{% if condition %}
{% block name %}
Template inheritance:
{% extends 'base.html' %}
{% block content %}
{% endblock %}Was this answer clear?