Twig advanced

Contents
Layouts with extends
Blocks
Common filters
path() and asset()

Layouts with extends

Pages share one layout instead of repeating the header and footer. The child template names its parent on the very first line:

{% extends "base.html.twig" %} <h1>Hello from the child page</h1>

Everything below that line normally lives inside blocks, which the next section covers.

Blocks

The layout declares named holes with block tags, and each page fills them with its own content:

{% block title %}My blog{% endblock %} {% block body %} <p>Page text goes here.</p> {% endblock %}

Common filters

Filters transform values with a pipe. They chain from left to right, so read them as a pipeline:

{{ title|upper }} {{ created|date("Y-m-d") }} {{ text|striptags|slice(0, 100) }}

path() and asset()

Functions build URLs and asset paths so templates never hardcode addresses. The path function takes a route name, and asset takes a file from under the public folder:

<a href="{{ path("app_hello") }}">Hello page</a> <img src="{{ asset("img/logo.png") }}">

Next: Doctrine setup

Article author: Arthur Isaev

Related articles
Development with PHP
What is Symfony and where it runs
Install Symfony
Your first page
Routes
Controllers
Twig basics
Twig advanced
Doctrine setup
Entities
Migrations
Repositories
Relations
Forms
Validation
Services and DI
JSON controllers
Serializer
Security intro
Users
Login form
Voters
Console commands
Events
Messenger
Mailer
Cache
Sessions
CSRF
Translations
Dotenv and env
Profiler
Testing
Fixtures
Pagination
File uploads
API Platform in one lesson
DQL
Transactions
Migrations advanced
Security advanced
HTTP client
Scheduler
Webhooks
Asset Mapper
Deployment
Performance
Capstone: blog
Capstone: JSON API
Modern Symfony tour
Hero roadmap: the whole course on one page

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: