I'd like to use Twig Tweak's drupal_view()
to render a view in my paragraph template. I have a couple entity reference fields on the paragraph and need the IDs of the referenced entities passed as contextual filter arguments.
I built a Contextual Filter String field formatter to format the contextual filter string with the hope that it could be passed directly as the argument's value. The formatter will return all
if the reference field is empty, otherwise it will return the referenced entity IDs as a string with AND/OR separators, e.g. 1,2,3
for AND or 1+2+3
for OR.
Inside my template, I'm attempting to render the view with the following twig:
{% set arg1 = content.field_arg1|render %}
{% set arg2 = content.field_arg2|render %}
{{ drupal_view('my_view', 'my_display', arg1, arg2) }}
But this does not work!
Rather than strings, my arg variables are actually Drupal\Core\Render\Markup objects so the arguments are not passed correctly to the view.
After researching, I've found that I can workaround this issue by filtering my arg variables with a php filter that returns a string. For example, using the trim filter works:
{% set arg1 = content.field_arg1|render|trim %}
{% set arg2 = content.field_arg2|render|trim %}
{{ drupal_view('my_view', 'my_display', arg1, arg2) }}
If possible, I would like to build a render array that doesn't require any fancy footwork in the template to pass the values to the drupal_view()
function. I.e. a render array where I can pass content.field_arg1
or content.field_arg|render
directly as the arguments. Is this possible?
Render arrays I've tried that did not work:
$inline_template = [
'#type' => 'inline_template',
'#template' => '{{ contextual_filter_string }}', // also tried with |trim filter here
'#context' => [
'contextual_filter_string' => '1+2+3',
],
];
$markup = [
'#markup' => '1+2+3',
];
$plain_text = [
'#plain_text' => '1+2+3',
];
Note: not shown in the above render arrays is cache metadata (tags) for the entities referenced in the field.
Yes, there are alternate ways to get these field values and pass them to drupal_view()
, however that's not what this question is about. I would like to use a Field Formatter to return a render array (I think I have to return a render array) that results in a string ready to be passed directly to drupal_view()
. This allows me to configure the format of the argument in the UI without touching code. I suspect this is impossible.
Some alternative approaches that I've considered:
- I could preprocess my paragraph and add these filter strings to the
$variables
array.
- I could build my own twig function to generate these contextual filter strings.
- I could get the values directly from the entity in my template, e.g.
paragraph.field_arg1.target_id
as Les Lim answered, but this doesn't work cleanly for multi-value fields.
Edit: It seems that this is impossible so accepting Les Lim's answer as the best alternative.