With the module "config pages" I've set some variables global to render in templates. In mytheme.theme I've added a function:

function mytheme_preprocess(array &$variables, $hook)
{
    $myConfigPage = \Drupal\config_pages\Entity\ConfigPages::config('config_name');
    $variables['my_settings'] = $myConfigPage->toArray();
}

In the config_pages I've created a link field. I would like to render them, but I get below output. How can I render the link in Twig?

  ^ array:3 [▼
      0 => array:3 [▼
        "uri" => "entity:node/186"
        "title" => "Title 3"
        "options" => []
      ]
      1 => array:3 [▼
        "uri" => "entity:node/189"
        "title" => "Title 1"
        "options" => []
      ]
      2 => array:3 [▼
        "uri" => "entity:node/195"
        "title" => "Title 2"
        "options" => []
      ]
    ]

Twig:

  {{ dd(my_settings.field_links) }}
  {% for link in my_settings.field_links %}
    <div class="field__item">
      {{ dd(link) }}
      {{ link.uri|render }}
      {{ link.title }}
    </div>
  {% endfor %}

None of above are working.

有帮助吗?

解决方案

You can render a link with core's link function:

This helper function accepts as first parameter the text and as second parameter the uri

Examples:

{{ link(item.title, item.uri, { 'class':['foo', 'bar', 'baz']} ) }}

In your case, this might look like:

{% for link_item in my_settings.field_links %}
  <div class="field__item">
    {{ link(link_item['title'], link_item['uri']) }}
    // or
    {{ link("My link text", "entity:node/123") }}
    // or
    {{ link("My link text", "internal:/some/internal/path") }}
    // or
    {{ link("My link text", "route:my.module.route_name") }}
    // or
    {{ link("My link text", "https://drupal.stackexchange.com/") }}
  </div>
{% endfor %}

Alternatively, and preferably imo, you can just render the field from the config_page entity (as with any content entity).

For example, in your preprocess:

// Load your config page.
$my_config_page = \Drupal::entityTypeManager()
  ->getStorage('config_pages')
  ->load('my_config_page_identifier');
// Build the render array for my links per the config page's `default` view mode.
$vars['my_links'] = $my_config_page->field_links->view('default');

Then, in twig:

{{ my_links }}
许可以下: CC-BY-SA归因
scroll top