user3116700 user3116700 - 4 months ago 36
Twig Question

How do you get the current url in Twig?

Inside a twig template I will check

if url is: http://example.com/search?keyword=test

{% set pageTitle = query %} query is test

else

{% set pageTitle = different %}

How I can do?

Thank you.

Answer

Slim-Views is your friend. Install it via composer and add the TwigExtension.

<?php
require 'vendor/autoload.php';

$app = new \Slim\Slim(array(
    'view' => new \Slim\Views\Twig()
));

$view = $app->view();

$view->parserExtensions = array(
    new \Slim\Views\TwigExtension(),
);

Now in your template you can access to the current url using:

{% if currentUrl() == "http://" ~ domain ~ "/search?keyword=" ~ keyword %}
  {% set pageTitle = query %}
{% else %}
  {% set pageTitle = different %}
{% endif %}
Comments