2018-11-08 16:14:14 +00:00
Starlette is not *strictly* coupled to any particular templating engine, but
Jinja2 provides an excellent choice.
2018-11-06 16:57:57 +00:00
2019-02-18 13:12:55 +00:00
Starlette provides a simple way to get `jinja2` configured. This is probably
what you want to use by default.
2018-11-06 16:57:57 +00:00
```python
from starlette.applications import Starlette
2019-02-18 13:12:55 +00:00
from starlette.templating import Jinja2Templates
2019-06-17 02:28:04 +00:00
from starlette.staticfiles import StaticFiles
2018-11-06 16:57:57 +00:00
2019-02-18 13:12:55 +00:00
templates = Jinja2Templates(directory='templates')
2018-11-06 16:57:57 +00:00
app = Starlette(debug=True)
2019-06-17 02:28:04 +00:00
app.mount('/static', StaticFiles(directory='static'), name='static')
2018-11-06 16:57:57 +00:00
@app .route('/')
async def homepage(request):
2019-02-18 13:12:55 +00:00
return templates.TemplateResponse('index.html', {'request': request})
2018-11-06 16:57:57 +00:00
```
2019-06-17 02:28:04 +00:00
Note that the [StaticFiles ](https://www.starlette.io/staticfiles/ ) application must be mounted and configured to serve the templates, and the incoming `request` instance must be included as part of the
2019-02-18 13:38:04 +00:00
template context.
2018-11-06 16:57:57 +00:00
2019-02-18 13:38:04 +00:00
The Jinja2 template context will automatically include a `url_for` function,
so we can correctly hyperlink to other pages within the application.
For example, we can link to static files from within our HTML templates:
2018-11-06 17:03:34 +00:00
```html
< link href = "{{ url_for('static', path='/css/bootstrap.min.css') }}" rel = "stylesheet" >
```
2019-02-18 13:12:55 +00:00
## Testing template responses
When using the test client, template responses include `.template` and `.context`
attributes.
```python
def test_homepage():
client = TestClient(app)
response = client.get("/")
assert response.status_code == 200
assert response.template.name == 'index.html'
assert "request" in response.context
```
2018-11-06 16:57:57 +00:00
## Asynchronous template rendering
Jinja2 supports async template rendering, however as a general rule
we'd recommend that you keep your templates free from logic that invokes
database lookups, or other I/O operations.
2019-02-18 13:38:04 +00:00
Instead we'd recommend that you ensure that your endpoints perform all I/O,
2018-11-06 16:57:57 +00:00
for example, strictly evaluate any database queries within the view and
include the final results in the context.