0

We are making a new website from an old Drupal 7 project. For each item within a view, I need to check if a file exists in order to enable or disable a link. In Drupal 7 we used file_exists() within the PHP template but we can't do that anymore with Twig.

I have opted for using the template_preprocess_views_view_unformatted(&$variables) function but I don't succeed in setting the variable properly.

function bootstrap5_preprocess_views_view_unformatted(&$variables) {
    $variables['#cache']['max-age'] = 0;

    $id_view = $variables['view']->id();
    // echo($id_view);
    switch ($id_view) {
        case 'recent_incidents_block':
            foreach ($variables['rows'] as $key => &$value) {
                
                // $value['content']['#row']->file_exists= "test";
                $variables['rows'][$key]['file_exists'] = "test";
            }
        break;
    }
}

Then in the view template:

{% for row in rows %}
  {% set file_exists = row.file_exists.value %}

But nothing gets printed with {{file_exists}}

3
  • A string like "test" is a primitive scalar datatype, it doesn't have any sub-properties or keys like .value. But whatever you are trying here, you are almost certainly doing it weird, Drupal's/Twig's {{ content }} render array is empty-aware, Twig has empty-operators for logic and you can drill entity references within Twig by appending .entity on the ER field.
    – Hudri
    May 24 at 9:52
  • Is this a drupal managed file? Can you just add a field to your view in the UI?
    – sonfd
    May 24 at 10:45
  • Try file_exits = row.file_exists no value.
    – No Sssweat
    May 28 at 4:41

0

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.