0

This question already has an answer here:

I need to add the url alias to the body tag. How can I do it in twig template?

{% set classes = [ root_path is empty ? 'frontpage' : root_path, root_path == 'node' ? 'node-' ~ node_type : '', logged_in ? 'authenticated' : 'anonymous' ] %}

marked as duplicate by leymannx, Bart, mradcliffe, Shawn Conn, AjitS Aug 9 '18 at 7:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

You can add your path in body class using template_preprocess_html . Here is below example.

function yourthemename_preprocess_html(&$variables) {
 $path = \Drupal::service('path.current')->getPath();
  $variables['attributes']['class'][] = $path;
 }
  • is there a way to do it in twig template? – User88002 Aug 2 '18 at 8:34
0

In html.html.twig

{%
set body_classes = [
logged_in ? 'user-logged-in',
not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
node_type ? 'node--type-' ~ node_type|clean_class,
db_offline ? 'db-offline',
]
%}

and write in body tag as

<body{{ attributes.addClass(body_classes) }}>
  • Not really working.I have a path /news/category, what is actually a taxonomy. Now it adds path-taxonomy. What I need is to have a "news" class in a body, which should be taken from url alias – User88002 Aug 2 '18 at 8:53
  • If you have path you can use split in twig. {% set foo = "news/category"|split('/') %} Then access array in twig by {{foo[0] }}. – Pankaj Yogi Aug 2 '18 at 9:03
  • And the question is how can I assign foo the alias path ? I used news/category as an example. I have many different pathes – User88002 Aug 2 '18 at 9:16
0

use method path('<current>').

{% set path=path('<current>') %}
<div class="{{path}}">

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