I need to display a field value available to paragraph.html.twig
in field.html.twig
.
I have a paragraph type called buttoncontainer
with a field name called field_background_color
. I have a paragraph type called button
nested within that as per the attached screenshot. I need to make the field_background_color
value available to field.html.twig
.
Let's say field_background_color
equates to #333333
In field.html.twig
I want to do something like:
<div style="background: {{ color }};">
{% for item in items %}
{{ item.content }}
{% endfor %}
</div>
Is this something that can be done with a preprocess function?
I tried
function mysubtheme_preprocess_paragraph(&$variables) {
$paragraph = $variables['paragraph'];
if ($paragraph->getType() === 'sidebar_button_repeater') {
if (!$paragraph->field_background_color->isEmpty()) {
$variables['color'] = $paragraph->get('field_background_color')->first()->getValue();
}
}
}
...but it won't output the value in field.html.twig
. The goal is simply to allow the user to determine the div background color behind the buttons they create.
Update: I tried this contributed preprocess function (changed mysubtheme to the relevant theme name btw)
use Drupal\paragraphs\ParagraphInterface;
function mysubtheme_preprocess_field(&$variables) {
$paragraph = $variables['element']['#object'];
if ($paragraph instanceof ParagraphInterface) {
if ($paragraph->getType() === 'sidebar_button_repeater') {
if (!$paragraph->field_background_color->isEmpty()) {
$variables['color'] = $paragraph->get('field_background_color')->value;
}
}
}
}
and added Color = {{ color }}
specifically to my field.html.twig
template but got no output unfortunately.
I also added:
{% set paragraph_parent = paragraph.getParentEntity() %}
{% set color = paragraph_parent.field_background_color.0.value %}
Color is {{ color }}.
...but that doesn't work in field.html.twig
either. It does however work in paragraph.html.twig
templates.
I found a very useful link at Access A Referenced Node's Fields - Field Level Templating that may inform a chnage to the code.I can return the NESTED paragraph field values using {{ item.content['#node'].field_background_color.value }}
but I can't return the PARENT paragraph field value.