0

I would like to include some custom html code only on a specific node. I created "parts" directory and put a custom twig template in it. (mytheme/templates/parts/custom_html.html.twig)

I then copied over the page.html.twig to my templates directory, and included the custom template with:

{% include directory ~ '/templates/parts/custom_html.html.twig' %}

I want to show this only on a certain node, say "node/2". I don't wan't to create a custom template just for this page, like "page--node--2.html.twig".

Is there a way of using a condition to just show this template on the specific node?

Kind of like this?

{% if 'node/2' %}
    {% include directory ~ '/templates/parts/custom_html.html.twig' %}
{% endif %}
  • This answer is a couple of years old, but it may help drupal.stackexchange.com/a/141104/42650 – mradcliffe Apr 19 '16 at 0:59
  • Thanks, but that post doesn't explain how to do the "if" statement. I'm adding the include in the main "page.html.twig" because I don't want to create a whole new node-specific template for just this one include. – barrakuda Apr 19 '16 at 2:20
1

If you want override page.html.twig for special node 2. You can try this code

{% if node.id == '2' %}
   {% include directory ~ '/templates/parts/custom_html.html.twig' %}
{% endif %}

if other template you need process in your function theme first:

YOUR_THEME_process_FUNCTION_THEME(&$vars) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $vars['node'] = $node;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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