Pass template literals into includes

408 Views Asked by At

I'd like to create DRY code by passing template literals into a twig {% includes 'X' %} as variables so they can be used in the includes code (examples below).

I have seen that you can pass a variable into a includes, like the below:

{% include 'template.html' with {'foo': 'bar'} %}

But since my code is going to be using the same includes template multiple times on the same page I need a bit more customization here.

Ideal what I want to do is set the viable when calling the includes and have that echoed into the template, example:

in page file:

{% set contact_img = 'path to image location' %}
{% include "/IMPORT/Specific/full_page_img_bg" with contact_img %}

in template

{% set transformed_{{ VARIABLE NAME PASSED HERE }} = craft.imager.transformImage({{ VARIABLE NAME PASSED HERE }}_for_transform, [
  { width: 2000, jpegQuality: 89 },
  { width: 1300, jpegQuality: 84 },
  { width: 750, jpegQuality: 82 },
  { width: 500, jpegQuality: 80 },
], { allowUpscale: false, mode: 'fit'}) %}

<img sizes="
  (max-width: 500px) 500px,
  (max-width: 750px) 750px,
  (max-width: 1280px) 1300px,
  2000px"
  srcset="{{ craft.imager.srcset(transformed_{{ VARIABLE NAME PASSED HERE }}) }}"
  alt="{{ {{ VARIABLE NAME PASSED HERE }}.title }}" 
  class="full-background-image"/>
<div class="full-gradient"></div>

Basically its like how in JS you can set a functions argument and that argument is outputted to the function, but you can call that function multiple times with different arguments i.e.

function callName(name) {
console.log(name)
}

callName('DEV-BOY')
#DEV-BOY
callName('BOY-BE_DEV')
#BOY-VE_DEV

Feel free to ask any question, I'm sure there must be a way to do this, thanks in advance - W

1

There are 1 best solutions below

2
On BEST ANSWER

You can create macros (which will operate) like functions, see https://twig.symfony.com/doc/2.x/tags/macro.html

Examples:

{% macro input(name, value, type = "text", size = 20) %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}"/>
{% endmacro %}

{% macro textarea(name, value, rows = 10, cols = 40) %}
    <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}">{{ value|e }}</textarea>
{% endmacro %}

In the examples above you can see that you enclose your macro between a macro and endmacro statement. The macro statement takes some parameters that you define, possibly with default values if needed. You can call them very much like functions, examples:

<p>{{ forms.input('username') }}</p>
<p>{{ forms.input('password', null, 'password') }}</p>

All examples were taken from the source linked at the start of this answer. You will need to place your parameterized includes into some macros. Ideally you would separate your parameterized include into a separate file where you could implement several macros of this type, import it and call the macros where you need them with the parameters you need.