1

I have a custom block Type with a Link field called "field_link" (for internal links only). Within my block Twig template I want to extract the URL of the link field. How can I do that? I read some post with similar problems, but none of the solutions seems to work so far.

What I tried so far:

{{ file_url(content.field_link.uri) }}
{{ file_url(content.field_link.0.url) }}

I only get "/" but there should be "/node/1"...

This is my standard block template:

<div{{ attributes.addClass(classes) }}>   
      {{ title_prefix }}
      {% if label %}
        <h2{{ title_attributes }}>{{ label }}</h2>
      {% endif %}
      {{ title_suffix }}
      {% block content %}
        {{ content }}
      {% endblock %}
</div>
1

I'm not sure you need to use file_url(), but you can use {{ content.field_link.0['#url'] }} as described in this question on stackoverflow.

0

You can get the URL and the value (text) this way:

{{ content.field_link.0['#url'] }}

{{ content.field_link.0['#title'] }}
0

In most templates (node, paragraph,...) you can access raw field values using
{{ entity_type.field_name.0.value }}. Sadly this does not work block templates. To make it work for custom content blocks you need to add a preprocess function:

function YOURTHEME_preprocess_block(array &$variables) {
  if ($variables['base_plugin_id'] == 'block_content') {
    $variables['block_content'] = $variables['elements']['content']['#block_content'];
  }
}

Now you can access your fields using {{ block_content.field_name.0.value }} (in case of link fields use {{ block_content.field_name.0.url }} as described here)

0

This code will be work properly for printing separate URL and Title of the link field in twig.

{{ content.field_link[0]['#url'] }}

{{ content.field_link[0]['#title'] }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.