FORSMILE
JA
Twig2021/02/02

[Twig] Getting Current URLs and Generating Paths

This post focuses on Twig, specifically the Twig extensions provided by Symfony.

Back to Blog

This post focuses on Twig, specifically the Twig extensions provided by Symfony.

Among these, I'd like to demonstrate how to retrieve and construct route paths.

Official: Twig Extensions Defined by Symfony

GETTING ROUTE NAMES AND PARAMETERS IN TWIG

Symfony's extensions allow you to use a global variable named `app`.

Getting the Route Name

For example, let's assume we have a page with the following route configuration (this configuration will be used for subsequent examples).

css
// Sample Root (Controller)
    /**
     * test product page.
     *
     * @Route(
     *      "/product/{id}/{type}",
     *      name="product_main", methods={"GET"},
     *      defaults={"type" = 1}
     * )
...
javascript
// Global Variables
// Route Name
app.request.attributes.get('_route')

// dump Variables
"product_main"

// Route Params
app.request.attributes.get('_route_params')

// dump Variables
array:2 [
  "id" => 13,
  "type" => 1
]

GENERATING PATHS IN TWIG

Here's how to use the `path` function in Symfony's Twig Extensions.

text
// Basic relative URL
path('route_name')

// Basic absolute URL
url('route_name')

Essentially, as shown above, you can generate relative and absolute URLs from a route name. You can also generate URLs with parameters, such as our `product_main` example. If a parameter does not have a default value, it must always be explicitly provided.

css
// product_main page sample
// current page
path(app.request.attributes.get('_route'), { 'id': app.request.attributes.get('_route_params').id})

// other id
path(app.request.attributes.get('_route'), { 'id': 11})
css
path(app.request.attributes.get('_route'), { 'id': 11, 'type': 2})

This was a brief introduction to retrieving current route information and generating URLs.

RECOMMENDED BOOKS ON TWIG

I haven't personally read any books exclusively dedicated to Twig, but I did find one available on Amazon Kindle.

📦
Amazon で関連書籍・ツールを検索
PHP Twig template engine
Amazonで探す →(アソシエイトリンク)