Based on this interesting article: DRY templating with Twig and Craft CMS. I found myself trying to update the approach with include
instead of macro
following reading I had about twig 2 and craftcms 3.
So basically there is my component
_hero-banner.twig
{# Defaults #}
{% set defaults = {
heroTitle : title is defined ? title : 'Title not set',
titleColor : color is defined ? color : null,
heroImage : image is defined ? image : null,
heroButton : button is defined ? button : null,
heroClasses : classes is defined ? classes : null
}
%}
{# Options #}
{% set options = options is defined ? defaults|merge(options) : defaults %}
{# Variables #}
{% set imageMobile = {
mode: 'crop',
width: 640,
height: 500,
quality: 75,
position: 'focus-point'
} %}
{# Output #}
<div class="row c-hero-banner" {% if options.heroImage %} style="background-image:url('{{ options.heroImage.one.getUrl(imageMobile) }}')" {% endif %}>
<div class="container">
<div class="col-xs-12 col-lg-6">
{# Display the entries #}
<h1 {% if options.titleColor %} class="t-text-white" {% endif %}>{{ options.heroTitle }}</h1>
{% if options.heroButton %}
<button type="button" class="o-button o-button--primary"> {{ options.heroButton }} </button>
{% endif %}
</div>
</div>
</div>
And there is my include
index.twig
{% set heroBannerOptions = {
title : homepage.mainTitle,
image : homepage.heroBanner,
color: true
}
%}
{% include 'components/_hero-banner.twig' with { options : heroBannerOptions } %}
Somehow I cannot pass the variables into the component and I cannot figure out why...
{{ dump(options) }}
in the included file?null
but options.title calls the proper info! Still need to figure out how to use that properly! :)