0

New guy here. Can someone explain what the proper way to pass a variable into an include? I'm using this:

{% include "singlepage" with { currentPage:'leaders' } %}

.. and I'm getting a Variable "currentPage" does not exist error.

In short, I have a template that I want to use for my singles pages, but I need to set a couple of variables for the template to use. So, I have a template for each single that simply sets the current page and then includes the single page template. Is this a good approach?

Thanks for any help.

2 Answers 2

2

You're probably looking for:

{% include "singlepage" with { 'currentPage': 'leaders' } %}

The key (the part before the :) needs to be a string, hence in quotes.

The relevant Twig template docs are here: https://twig.symfony.com/doc/2.x/tags/include.html#include

3
  • No, that didn't do it. The singlepage template is still unaware of the currentPage variable. Could it be that singlepage is extending another template? Is it some kind of nesting issue? Any help appreciated. In the mean time, I'll go over the docs again.
    – Mosswalker
    Commented Dec 12, 2017 at 16:46
  • 1
    Got this going by restructuring my templates. Not sure the exact reason I was getting the error but when I moved the variable declarations above the "extends" call the inner "include" had access to the variables.
    – Mosswalker
    Commented Dec 15, 2017 at 22:27
  • Fair enough... would you mind adding that as an official answer in case it helps someone in the future?
    – Brad Bell
    Commented Dec 17, 2017 at 3:00
0

Got this going by restructuring my templates. Not sure the exact reason I was getting the error but when I moved the variable declarations above the "extends" call the inner "include" had access to the variables. –

2
  • 1
    A more detailed explanation of how to include with variables would be much appreciated. What was your solution? Can you share? Commented Jul 9, 2018 at 19:56
  • I wish I could tell you what I changed, but this was resolved just as I was getting the hand of twig/craft. I can say that I do use include with in my templates like this:{% set vars = {'title' : title } %} {% include "_includes/_header.html" with vars %}
    – Mosswalker
    Commented Jul 11, 2018 at 22:27

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.