7

I'm new to twig and drupal 8 and finding it hard to access page titles. I want to apply a class to a page title on certain pages, all of which share a sub-directory in the URL path. I'm working with a page-title.html.twig file and want to do something like this:

{{ title_prefix }}
{% if title %}
  {% if <url contains "/services/"> %}
    <h1 {{ title_attributes.addClass('services-title') }}>{{ title }}</h1>
  {% else %}
    <h1 {{ title_attributes.addClass('page-title') }}>{{ title }}</h1>
  {% endif %}
{% endif %}
{{ title_suffix }}

I'm assuming this is possible, I just can't figure out how to check the URL for the desired string.

1 Answer 1

11

Use the "in" operator:

{% if '/services/' in url %}

More information: http://twig.sensiolabs.org/doc/templates.html#containment-operator

If you didn't do it already, put this preprocess function in the file mytheme.theme in your theme directory:

function mytheme_preprocess_page_title(&$variables) {
  $variables['url'] = $_SERVER['REQUEST_URI'];
  $variables['#cache']['contexts'][] = 'url.path';
}

Edit: By moving the code from page inside a block we need to provide a cache context.

10
  • 2
    I've done this and the 'if' statement is executing with no errors, but always evaluates to false, even on the '/services/' pages. So I end up with 'page-title' no matter what. Any idea what is going wrong? I did create the .theme file and replaced 'mytheme' with the correct theme name and cleared the caches. Commented Apr 6, 2016 at 15:48
  • do I need to be escaping those slashes in '/services/' perhaps? Commented Apr 6, 2016 at 15:52
  • I've just put the complete code from my answer in a page template, it works, with slashes. You don't need to escape them. Be sure, that the preprocess sets the var 'url'.
    – 4uk4
    Commented Apr 6, 2016 at 16:15
  • {{ url }} isn't returning anything. I did not have a .theme file before, should that be declared in one of the yml files or something? Commented Apr 6, 2016 at 16:20
  • 2
    I found it, we are in different templates, you are using page-title, my code is for page. You have to move php and twig in the same template.
    – 4uk4
    Commented Apr 6, 2016 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.