1

To separate code and avoid duplication I am trying to split up recurring pieces of twig code into partials (think of a nav or a block of services for example).

I tried using include but Craft requires me to register a template path. This is also stated in the docs.

I'm not really sure this is the best way to do it since I would litter my "Sections" with "Singles" which would just function as nothing more include templates.

For example in my home.twig I have the following piece of code:

<div>
    <div class="container mx-auto px-4 pb-16">
        {% include 'pages/home/dienstenGrid.twig' %}
    </div>
</div>

Which would render the corresponding include template. But to be able to do this I have to register this "section" enter image description here

Something about this feels gross, and I was wondering if there's a better way to go about this issue. If This is the way I will use it this way (Star Wars: The Mandalorian pun intended)

  • Couldn't you define a macro which returns your snippet for example and then simply call {{ macros.dienstenGrid() }} instead? Macros are defined in /craft/templates/partials/macros.twig as far as I remember – Campiotti Dec 2 at 14:48
  • That's what I was thinking, I found a thread on this stackexchange which pointed out macros. But it seems that macros are more used to create certain markup with variable inputs (like form tags) etc. But I might use macro's. – ArneDB Dec 2 at 14:49
  • Are you extending a base layout template? – Oli Dec 2 at 19:30
  • Yes I am. (I have to add more charachters to be able to comment) – ArneDB Dec 2 at 20:18
  • This shouldn't be the case, you can create any twig file without add an associate section to it. Just when you do that, it's a good idea to add _ before the name. Just like _partials/home/dienstenGrid.twig. Then this twig file/template is not visitable by just use the file path. – Parry Huang Dec 3 at 0:05

Your Answer

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

Browse other questions tagged or ask your own question.