如何从模板文件中主题链接? -- theming 领域 和 8 领域 drupal 相关 的问题

How do I theme a link from a template file?


11
vote

问题

中文

删除模板是呈现类的链接列表。基本:

  {{ mylink }}   

Twig代码将输出类似于

的东西
  <a href="#" class="someclass" >the text</a>   

并非所有链接都有课程。我想编写一个枝条模板,而不是输出这样的东西:

  <a href="#" class="someclass" >   <span class="sprite someclass" ></span>   the text</a>   

我尝试了什么:

  1. 我查找了删除的枝条模板。不幸的是,似乎链接不是由枝模板呈现的。

  2. 我尝试更新像

    这样的枝条变量
      set mylink['#title'] = "<span>...</span>" ~ mylink['#title']   

    但它不会让我这样做。

英文原文

A twig template is rendering a list of links that come with classes. The basic:

{{ mylink }} 

twig code will output something like

<a href="#" class="someclass" >the text</a> 

Not all links have classes. I want to write a twig template that will instead output something like this:

<a href="#" class="someclass" >   <span class="sprite someclass" ></span>   the text</a> 

What I've tried:

  1. I looked for the twig template to override. Unfortunately it seems that links are not rendered by a twig template.

  2. I tried updating the twig variable like

    set mylink['#title'] = "<span>...</span>" ~ mylink['#title'] 

    But it won't let me do that.

     
 
 

回答列表

7
 
vote
vote
最佳答案
 

这是一个只有需要这种处理的特定领域的枝条; 它不是各处所有链接的通用解决方案。

一些-template.twig:

  <ul class="field--name-field-links">   {% for item in content.field_links %}   {% if item['#title'] %}     <li>       <a href="{{ item['#url'] }}" class="{{ item['#options'].attributes.class|join(' ') }}" >         {% if item['#options']['attributes']['class'] %}           <span class="sprite {{ item['#options']['attributes']['class']|join(" ") }}"></span>         {% endif %}         {{ item['#title'] }}       </a>     </li>   {% endif %}   {% endfor %} </ul>   
 

Here's a twig only solution for a particular field that needs this treatment; it's not a generic solution for all links everywhere.

some-template.twig:

<ul class="field--name-field-links">   {% for item in content.field_links %}   {% if item['#title'] %}     <li>       <a href="{{ item['#url'] }}" class="{{ item['#options'].attributes.class|join(' ') }}" >         {% if item['#options']['attributes']['class'] %}           <span class="sprite {{ item['#options']['attributes']['class']|join(" ") }}"></span>         {% endif %}         {{ item['#title'] }}       </a>     </li>   {% endif %}   {% endfor %} </ul> 
 
 
     
     
6
 
vote

我找不到一种方法来改变树枝中的链接"#markup" ,但有方法可以在渲染阶段改变它。
我制作了这个小模块,它扩展了链接功能,并使其能够在渲染的链接注入一些内容。所以让我们做一些代码,我会在评论中解释...

模块文件结构:

  better_link  | - src    | - Element      | BetterLink.php    | - Plugin      | - FieldFormatter        | BetterLinkFormatter.php  | better_link.info.yml  | better_link.module   

文件内容:

bettle_link.info.yml

  name: 'Better link' type: module package: 'Field types' description: 'A very nice better link' core: '8.x' dependencies:   - field   - link   

betterd_link.module

  <?php  use DrupalCoreRoutingRouteMatchInterface;  /**  * Implements hook_help().  * Just some words about the module.  */ function better_link_help($route_name, RouteMatchInterface $route_match) {   switch ($route_name) {     case 'help.page.better_link':       $output = '';       $output .= '<h3>' . t('About') . '</h3>';       $output .= '<p>' . t('Provide a improved link formatter and renderer for a custom link markup.') . '</p>';       $output .= '<p>' . t('Will be added a span html tag right before link content.') . '</p>';       $output .= '<p>' . t(' - Link class can be added throught manage display.') . '</p>';       $output .= '<p>' . t(' - Span class can be added throught manage display.') . '</p>';       return $output;   } }   

beyentlinkformatter.php

  <?php  /**  * @file  * Contains Drupaletter_linkPluginFieldFieldFormatterBetterLinkFormatter.  */  namespace Drupaletter_linkPluginFieldFieldFormatter;  use DrupalCoreFieldFieldItemListInterface; use DrupalComponentUtilityHtml; use DrupalComponentUtilityUnicode; use DrupalCoreFormFormStateInterface; use DrupallinkPluginFieldFieldFormatterLinkFormatter;  /** * Plugin implementation of the 'better_link' formatter. * * @FieldFormatter( *   id = "better_link", *   label = @Translation("Better Link"), *   field_types = { *     "link" *   } * ) */ class BetterLinkFormatter extends LinkFormatter {   /**    * {@inheritdoc}    */   public static function defaultSettings() {     $settings = parent::defaultSettings();     //Keeping simple...     $settings['span_class'] = '';     $settings['link_class'] = '';     //... but feel free to add, tag_name, buble_class, wraper_or_inside     return $settings;   }    /**    * {@inheritdoc}    */   public function settingsForm(array $form, FormStateInterface $form_state) {     $form = parent::settingsForm($form, $form_state);     //Make sure that you always store a name that can be used as class     $settings['link_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('link_class')));     $settings['span_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('span_class')));     $this->setSettings($settings);      $form['link_class'] = array(       '#title' => $this->t('Inject this class to link'),       '#type' => 'textfield',       '#default_value' => $settings['link_class'],     );     $form['span_class'] = array(       '#title' => $this->t('Inject this class to span'),       '#type' => 'textfield',       '#default_value' => $settings['span_class'],     );     return $form;   }    /**    * {@inheritdoc}    */   public function settingsSummary() {     $summary = parent::settingsSummary();     //Same here. Somehow if you use setSettings here don't reflect in settingsForm     $settings['link_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('link_class')));     $settings['span_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('span_class')));     $this->setSettings($settings);      //Summary is located in the right side of your field (in manage display)     if (!empty($settings['link_class'])) {       $summary[] = t("Class '@class' will be used in link element.", array('@class' => $settings['link_class']));     }     else {       $summary[] = t('No class is defined for link element.');     }      if (!empty($settings['span_class'])) {       $summary[] = t("Class '@class' will be used in span element.", array('@class' => $settings['span_class']));     }     else {       $summary[] = t('No class is defined for span element.');     }      return $summary;   }    /**    * {@inheritdoc}    */   public function viewElements(FieldItemListInterface $items, $langcode) {     $elements = parent::viewElements($items, $langcode);     //Yeah, here too, same 'problem'.     $settings['link_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('link_class')));     $settings['span_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('span_class')));      foreach ($items as $delta => $item) {       //Lets change the render element type and inject some options that will       //be used in render phase       if (isset($elements[$delta]['#type'])) {         $elements[$delta]['#type'] = 'better_link';         $elements[$delta]['#options']['#link_class'] = $settings['link_class'];         $elements[$delta]['#options']['#span_class'] = $settings['span_class'];       }     }     //Next step, render phase, see ya...     return $elements;   } }   

betterlink.php

  <?php  /**  * @file  * Contains Drupaletter_linkElementBetterLink.  */  namespace Drupaletter_linkElement;  use DrupalCoreRenderElementLink;  /**  * Provides a better_link render element. Almost the same as link.  *  * @RenderElement("better_link")  */ class BetterLink extends Link {   /**    * {@inheritdoc}    */   public function getInfo() {     $class = get_class($this);     return array(       '#pre_render' => array(         array($class, 'preRenderLink'),       ),     );   }    /**    * {@inheritdoc}    */   public static function preRenderLink($element) {     //Hello again. Lets work.     //Before Drupal create the rendered link element lets inject our stuff...     //...Our class to link     $element['#options']['attributes']['class'][] = $element['#options']['#link_class'];     //...Build span classes     $span_classes = $element['#options']['#span_class'] . ' ' . $element['#options']['#link_class'];     //...And get rid them.     unset($element['#options']['#link_class']);     unset($element['#options']['#span_class']);     //Lets Drupal do the hard work     $element = parent::preRenderLink($element);     //Here is where the magic happens ;)     if (!empty($element['#markup'])) {       //Inject our span right before link content.       $element['#markup'] = str_replace('">', ""><span class='$span_classes'></span>", $element['#markup']);       //Side comment - Thank you spaceless, str_replace can be used here     }     //Now, whatever you change in your url or another object will not maintain,     //the only thing that will be returned in the end is     //$element['#markup'], so this is the only thing you can change.     return $element;   } }   

重要:

这将适用于所有链接字段,确定,如果您在管理显示中更改其格式化器(编辑节点类型)。

我希望这可能有用。

对@artfulrobot:你能测试这个模块吗?我认为翻译问题可以通过这种方式解决。

 

I'm not found a way to change link '#markup' in twig, but there is way to change it on render phase.
I made this little module that extend Link functionality and make it able to inject some stuff on rendered link. So lets do some code, I will explain in comments...

Module file structure:

better_link  | - src    | - Element      | BetterLink.php    | - Plugin      | - FieldFormatter        | BetterLinkFormatter.php  | better_link.info.yml  | better_link.module 

File contents:

better_link.info.yml

name: 'Better link' type: module package: 'Field types' description: 'A very nice better link' core: '8.x' dependencies:   - field   - link 

better_link.module

<?php  use Drupal\Core\Routing\RouteMatchInterface;  /**  * Implements hook_help().  * Just some words about the module.  */ function better_link_help($route_name, RouteMatchInterface $route_match) {   switch ($route_name) {     case 'help.page.better_link':       $output = '';       $output .= '<h3>' . t('About') . '</h3>';       $output .= '<p>' . t('Provide a improved link formatter and renderer for a custom link markup.') . '</p>';       $output .= '<p>' . t('Will be added a span html tag right before link content.') . '</p>';       $output .= '<p>' . t(' - Link class can be added throught manage display.') . '</p>';       $output .= '<p>' . t(' - Span class can be added throught manage display.') . '</p>';       return $output;   } } 

BetterLinkFormatter.php

<?php  /**  * @file  * Contains \Drupal\better_link\Plugin\Field\FieldFormatter\BetterLinkFormatter.  */  namespace Drupal\better_link\Plugin\Field\FieldFormatter;  use Drupal\Core\Field\FieldItemListInterface; use Drupal\Component\Utility\Html; use Drupal\Component\Utility\Unicode; use Drupal\Core\Form\FormStateInterface; use Drupal\link\Plugin\Field\FieldFormatter\LinkFormatter;  /** * Plugin implementation of the 'better_link' formatter. * * @FieldFormatter( *   id = "better_link", *   label = @Translation("Better Link"), *   field_types = { *     "link" *   } * ) */ class BetterLinkFormatter extends LinkFormatter {   /**    * {@inheritdoc}    */   public static function defaultSettings() {     $settings = parent::defaultSettings();     //Keeping simple...     $settings['span_class'] = '';     $settings['link_class'] = '';     //... but feel free to add, tag_name, buble_class, wraper_or_inside     return $settings;   }    /**    * {@inheritdoc}    */   public function settingsForm(array $form, FormStateInterface $form_state) {     $form = parent::settingsForm($form, $form_state);     //Make sure that you always store a name that can be used as class     $settings['link_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('link_class')));     $settings['span_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('span_class')));     $this->setSettings($settings);      $form['link_class'] = array(       '#title' => $this->t('Inject this class to link'),       '#type' => 'textfield',       '#default_value' => $settings['link_class'],     );     $form['span_class'] = array(       '#title' => $this->t('Inject this class to span'),       '#type' => 'textfield',       '#default_value' => $settings['span_class'],     );     return $form;   }    /**    * {@inheritdoc}    */   public function settingsSummary() {     $summary = parent::settingsSummary();     //Same here. Somehow if you use setSettings here don't reflect in settingsForm     $settings['link_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('link_class')));     $settings['span_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('span_class')));     $this->setSettings($settings);      //Summary is located in the right side of your field (in manage display)     if (!empty($settings['link_class'])) {       $summary[] = t("Class '@class' will be used in link element.", array('@class' => $settings['link_class']));     }     else {       $summary[] = t('No class is defined for link element.');     }      if (!empty($settings['span_class'])) {       $summary[] = t("Class '@class' will be used in span element.", array('@class' => $settings['span_class']));     }     else {       $summary[] = t('No class is defined for span element.');     }      return $summary;   }    /**    * {@inheritdoc}    */   public function viewElements(FieldItemListInterface $items, $langcode) {     $elements = parent::viewElements($items, $langcode);     //Yeah, here too, same 'problem'.     $settings['link_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('link_class')));     $settings['span_class'] = Html::cleanCssIdentifier(Unicode::strtolower($this->getSetting('span_class')));      foreach ($items as $delta => $item) {       //Lets change the render element type and inject some options that will       //be used in render phase       if (isset($elements[$delta]['#type'])) {         $elements[$delta]['#type'] = 'better_link';         $elements[$delta]['#options']['#link_class'] = $settings['link_class'];         $elements[$delta]['#options']['#span_class'] = $settings['span_class'];       }     }     //Next step, render phase, see ya...     return $elements;   } } 

BetterLink.php

<?php  /**  * @file  * Contains \Drupal\better_link\Element\BetterLink.  */  namespace Drupal\better_link\Element;  use Drupal\Core\Render\Element\Link;  /**  * Provides a better_link render element. Almost the same as link.  *  * @RenderElement("better_link")  */ class BetterLink extends Link {   /**    * {@inheritdoc}    */   public function getInfo() {     $class = get_class($this);     return array(       '#pre_render' => array(         array($class, 'preRenderLink'),       ),     );   }    /**    * {@inheritdoc}    */   public static function preRenderLink($element) {     //Hello again. Lets work.     //Before Drupal create the rendered link element lets inject our stuff...     //...Our class to link     $element['#options']['attributes']['class'][] = $element['#options']['#link_class'];     //...Build span classes     $span_classes = $element['#options']['#span_class'] . ' ' . $element['#options']['#link_class'];     //...And get rid them.     unset($element['#options']['#link_class']);     unset($element['#options']['#span_class']);     //Lets Drupal do the hard work     $element = parent::preRenderLink($element);     //Here is where the magic happens ;)     if (!empty($element['#markup'])) {       //Inject our span right before link content.       $element['#markup'] = str_replace('">', "\"><span class='$span_classes'></span>", $element['#markup']);       //Side comment - Thank you spaceless, str_replace can be used here     }     //Now, whatever you change in your url or another object will not maintain,     //the only thing that will be returned in the end is     //$element['#markup'], so this is the only thing you can change.     return $element;   } } 

Important:

This will work for all of your link fields, sure, if you change its formatter in manage display (editing your node type).

I hope that can be useful.

Request to @artfulrobot: Can you test this module? I think that translate issue can be solved this way.

 
 
         
         
4
 
vote

您可以只添加渲染数组到#title,如:

  ['#title'] = array('#markup' => '<i class="my-icons">yummy</i>' . $item['content']['#title']);   

旧的长答:

您可以覆盖链接生成器服务

创建一个模块(rederned_linkgenerator),具有info文件备用_linkgenerator.info.yml

  name: Alternative LinkGenerator type: module description: Adds alternative link generation. core: 8.x   

使一个名为rederted_linkgenerator.services.yml

的文件
  services:   alternative_linkgenerator.link_generator:     class: Drupalalternative_linkgeneratorAlternativeLinkGenerator   

next是要创建类,请添加名为"src" 的文件夹(按照PSR-4自动加载标准之后),并在此文件中称为ExternativelinkGenerator.php。 (这是1:1副本,您需要调整您的东西)

  <ul class="field--name-field-links">   {% for item in content.field_links %}   {% if item['#title'] %}     <li>       <a href="{{ item['#url'] }}" class="{{ item['#options'].attributes.class|join(' ') }}" >         {% if item['#options']['attributes']['class'] %}           <span class="sprite {{ item['#options']['attributes']['class']|join(" ") }}"></span>         {% endif %}         {{ item['#title'] }}       </a>     </li>   {% endif %}   {% endfor %} </ul> 0  

编辑services.yml(通常在Drupal 8 CodeBase中的站点/默认/ services.yml)并添加以下内容:

  <ul class="field--name-field-links">   {% for item in content.field_links %}   {% if item['#title'] %}     <li>       <a href="{{ item['#url'] }}" class="{{ item['#options'].attributes.class|join(' ') }}" >         {% if item['#options']['attributes']['class'] %}           <span class="sprite {{ item['#options']['attributes']['class']|join(" ") }}"></span>         {% endif %}         {{ item['#title'] }}       </a>     </li>   {% endif %}   {% endfor %} </ul> 1  

props goes

 

you can just add a render array to #title, like:

['#title'] = array('#markup' => '<i class="my-icons">yummy</i>' . $item['content']['#title']); 

Old long answer:

You can override the link generator service

Create a module (alternative_linkgenerator), with an info file alternative_linkgenerator.info.yml

name: Alternative LinkGenerator type: module description: Adds alternative link generation. core: 8.x 

Make a file called alternative_linkgenerator.services.yml

services:   alternative_linkgenerator.link_generator:     class: Drupal\alternative_linkgenerator\AlternativeLinkGenerator 

Next is to create the class, add a folder named xe2x80x9csrcxe2x80x9d (following PSR-4 autoloading standards) and within this a file called AlternativeLinkGenerator.php. (This is a 1:1 copy, you need to adapt the things for your)

class AlternativeLinkGenerator extends LinkGeneratorInterface {    /**    * The url generator.    *    * @var \Drupal\Core\Routing\UrlGeneratorInterface    */   protected $urlGenerator;    /**    * The module handler firing the route_link alter hook.    *    * @var \Drupal\Core\Extension\ModuleHandlerInterface    */   protected $moduleHandler;    /**    * The renderer service.    *    * @var \Drupal\Core\Render\RendererInterface    */   protected $renderer;    /**    * Constructs a LinkGenerator instance.    *    * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator    *   The url generator.    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler    *   The module handler.    * @param \Drupal\Core\Render\RendererInterface $renderer    *   The renderer service.    */   public function __construct(UrlGeneratorInterface $url_generator, ModuleHandlerInterface $module_handler, RendererInterface $renderer) {     $this->urlGenerator = $url_generator;     $this->moduleHandler = $module_handler;     $this->renderer = $renderer;   }    /**    * {@inheritdoc}    */   public function generateFromLink(Link $link) {     return $this->generate($link->getText(), $link->getUrl());   }    /**    * {@inheritdoc}    *    * For anonymous users, the "active" class will be calculated on the server,    * because most sites serve each anonymous user the same cached page anyway.    * For authenticated users, the "active" class will be calculated on the    * client (through JavaScript), only data- attributes are added to links to    * prevent breaking the render cache. The JavaScript is added in    * system_page_attachments().    *    * @see system_page_attachments()    */   public function generate($text, Url $url) {     // Performance: avoid Url::toString() needing to retrieve the URL generator     // service from the container.     $url->setUrlGenerator($this->urlGenerator);      if (is_array($text)) {       $text = $this->renderer->render($text);     }      // Start building a structured representation of our link to be altered later.     $variables = array(       'text' => $text,       'url' => $url,       'options' => $url->getOptions(),     );      // Merge in default options.     $variables['options'] += array(       'attributes' => array(),       'query' => array(),       'language' => NULL,       'set_active_class' => FALSE,       'absolute' => FALSE,     );      // Add a hreflang attribute if we know the language of this link's url and     // hreflang has not already been set.     if (!empty($variables['options']['language']) && !isset($variables['options']['attributes']['hreflang'])) {       $variables['options']['attributes']['hreflang'] = $variables['options']['language']->getId();     }      // Ensure that query values are strings.     array_walk($variables['options']['query'], function(&$value) {       if ($value instanceof MarkupInterface) {         $value = (string) $value;       }     });      // Set the "active" class if the 'set_active_class' option is not empty.     if (!empty($variables['options']['set_active_class']) && !$url->isExternal()) {       // Add a "data-drupal-link-query" attribute to let the       // drupal.active-link library know the query in a standardized manner.       if (!empty($variables['options']['query'])) {         $query = $variables['options']['query'];         ksort($query);         $variables['options']['attributes']['data-drupal-link-query'] = Json::encode($query);       }        // Add a "data-drupal-link-system-path" attribute to let the       // drupal.active-link library know the path in a standardized manner.       if ($url->isRouted() && !isset($variables['options']['attributes']['data-drupal-link-system-path'])) {         // @todo System path is deprecated - use the route name and parameters.         $system_path = $url->getInternalPath();         // Special case for the front page.         $variables['options']['attributes']['data-drupal-link-system-path'] = $system_path == '' ? '<front>' : $system_path;       }     }      // Remove all HTML and PHP tags from a tooltip, calling expensive strip_tags()     // only when a quick strpos() gives suspicion tags are present.     if (isset($variables['options']['attributes']['title']) && strpos($variables['options']['attributes']['title'], '<') !== FALSE) {       $variables['options']['attributes']['title'] = strip_tags($variables['options']['attributes']['title']);     }      // Allow other modules to modify the structure of the link.     $this->moduleHandler->alter('link', $variables);      // Move attributes out of options since generateFromRoute() doesn't need     // them. Include a placeholder for the href.     $attributes = array('href' => '') + $variables['options']['attributes'];     unset($variables['options']['attributes']);     $url->setOptions($variables['options']);      // External URLs can not have cacheable metadata.     if ($url->isExternal()) {       $generated_link = new GeneratedLink();       $attributes['href'] = $url->toString(FALSE);     }     else {       $generated_url = $url->toString(TRUE);       $generated_link = GeneratedLink::createFromObject($generated_url);       // The result of the URL generator is a plain-text URL to use as the href       // attribute, and it is escaped by \Drupal\Core\Template\Attribute.       $attributes['href'] = $generated_url->getGeneratedUrl();     }      if (!SafeMarkup::isSafe($variables['text'])) {       $variables['text'] = Html::escape($variables['text']);     }     $attributes = new Attribute($attributes);     // This is safe because Attribute does escaping and $variables['text'] is     // either rendered or escaped.     return $generated_link->setGeneratedLink('<a' . $attributes . '>' . $variables['text'] . '</a>');   }  } 

Edit services.yml (normally at sites/default/services.yml in your Drupal 8 codebase) and add the following:

  services:     link_generator:       alias: alternative_linkgenerator.link_generator 

props goes here

 
 
         
         
0
 
vote

尝试此代码:

  <ul class="field--name-field-links">   {% for item in content.field_links %}   {% if item['#title'] %}     <li>       <a href="{{ item['#url'] }}" class="{{ item['#options'].attributes.class|join(' ') }}" >         {% if item['#options']['attributes']['class'] %}           <span class="sprite {{ item['#options']['attributes']['class']|join(" ") }}"></span>         {% endif %}         {{ item['#title'] }}       </a>     </li>   {% endif %}   {% endfor %} </ul> 2  

{% - endif%}

或者这个(它来自: https://github.com/liip/bund_drupal_starterkit_theme/blob/master/templates/navigation/links--language-block.html.twig ):

  <ul class="field--name-field-links">   {% for item in content.field_links %}   {% if item['#title'] %}     <li>       <a href="{{ item['#url'] }}" class="{{ item['#options'].attributes.class|join(' ') }}" >         {% if item['#options']['attributes']['class'] %}           <span class="sprite {{ item['#options']['attributes']['class']|join(" ") }}"></span>         {% endif %}         {{ item['#title'] }}       </a>     </li>   {% endif %}   {% endfor %} </ul> 3  
 

try this code:

{% if links -%}   {%- if heading -%}     {%- if heading.level -%}   <{{ heading.level }}{{ heading.attributes }}>{{ heading.text }}</{{ heading.level }}> {%- else -%}   <h2{{ heading.attributes }}>{{ heading.text }}</h2>    {%- endif -%}   {%- endif -%}   <ul{{ attributes }}> {%- for item in links -%}   <li{{ item.attributes }}>         {%- if item.link -%}      <!--{{ item.link }} this line must stay -->      <a href="{{ item.link['#url'] }}"       {{ item.attributes.addClass(classes) }}       {{ item.attributes.setAttribute('title', item.text ) }}       {{ item.attributes.setAttribute('lang', item.link['#options'].language.id ) }}       {{ item.attributes.setAttribute('aria-label', item.text ) }}>         <img alt="{{ item.link['#title'] }}" src="/themes/subtheme/img/flag_{{ item.link['#options'].language.id }}.jpg" class="align-center">     </a>       {%- elseif item.text_attributes -%}       <span{{ item.text_attributes }}>{{ item.text }}</span>     {%- else -%}       {{ item.text }}     {%- endif -%}   </li> {%- endfor -%} 

{%- endif %}

or this one (it comes from: https://github.com/liip/bund_drupal_starterkit_theme/blob/master/templates/navigation/links--language-block.html.twig):

{% if links and links|length > 1 -%}   <ul>     {%- for item in links -%}       <li>         {%- if item.link -%}        <!--{{ item.link }} to do: remove this line without breaking the urls -->        {% if item.link['#options'].language.id == current_language %}         {% set classes = ['active'] %}       {% else %}         {% set classes = [''] %}       {% endif %}       {% set url = path(item.link['#url'].routeName, item.link['#url'].routeParameters, item.link['#url'].options) %}      {%- else -%}       {% set classes = ['disabled'] %}       {% set url = '#' %}     {%- endif -%}      <a href="{{ url }}"       {{ item.attributes.addClass(classes) }}       {{ item.attributes.setAttribute('title', item.text ) }}       {{ item.attributes.setAttribute('lang', item.link['#options'].language.id ) }}       {{ item.attributes.setAttribute('aria-label', item.text ) }}>         {{ item.link['#options'].language.id | upper }}     </a>   </li> {%- endfor -%}   </ul> {%- endif %} 
 
 

相关问题

3  如何使用视图使用枝条模板?  ( How do i use twig templates with views ) 
我正试图弄清楚如何使用视图使用枝条模板。目前我只是在视图中使用枝条,但我确定我可以使用枝条文件来覆盖视图的样式。 e.g。 <div class="editorHover"> <div class="editorInside"> {{ field_category }} {{ t...

20  验证字段不为空  ( Verify a field is not empty ) 
如何检查节点模板中是否为空的最佳方法。 在node - example.html.twig中我们可以使用"内容" 变量。 我无法使用检查,如检查块 {% if content.field_example %} 我可以使用这样的东西: {% if content.field_example['#ob...

0  实现Mega菜单的任何简单方法? [关闭]  ( Any easy way of implementing a mega menu ) 
关闭。这个问题是基于意见的。它目前不接受答案。 想要改进这个问题?更新问题,以便通过编辑此帖的事实和引用来回答。 closed 3年前。 ...

4  如何将计算机数据从主题预处理功能传递给Twig模板?  ( How to pass computed data from theme preprocess functions to twig templates ) 
我的一般问题是:我需要从PHP计算一些数据,通常使用Drupal API,然后将计算值传递给枝模板(为了显示它)。 例如:我有一个名为 node--dog.html.twig 和在这个模板里面的模板,我需要显示狗 s的总数网站。为此,我将使用 Drupal::entityQuery API来计算从PHP The T...

4  自定义主题自定义链接字段的HTML  ( Customize the html of a link field from a custom theme ) 
我是一个名为 field_home_link 的链接字段,附加到内容类型命名为 Home ,我我试图自定义如何从自定义主题内部呈现为HTML。 而不是默认生成的html: <a tabindex="0" href="http://example.com">Link text</a> 我需要呈现此HTML,在...

2  如何在节点模板中打印分类术语字段?  ( How to print taxonomy terms field in node templates ) 
如何在Drupal 8的节点模板中显示节点分类术语字段? 我们在drupal 7通过将此代码添加到node.tpl.php文件: print render($content['field_tags']); 我尝试在drupal 8中添加以下代码: {{ content.field_tags }} ...

0  我创建的新视图的代码在哪里?  ( Where is the code of a new view ive created ) 
我正在使用Drupal 7,其中Zen的启动主题。我在块上创建了一个视图,现在我需要自定义 html / css 的某些部分,以便只添加媒体查询(CSS部分)并添加 <a> 标记 display:none 对于桌面版和 display:block 移动。所以我需要修改此视图的HTML和CSS。我正在寻找这个视图的PH...

47  如何从Twig模板中获取链接字段的有效URL?  ( How to get the valid url of a link field from within a twig template ) 
我有一个名为 field_my_link (机名称)的链接字段。 在Twig模板中,我可以使用以下方式获取链接的URL值: {{ node.field_my_link.uri }} 如果在链接的URL内部有一个外部 URL,例如, http://example.com 它适用于。 但是,如果在链接的URL...

7  如何更改语言项链接?  ( How do i alter a language item link ) 
我正在寻找在某些情况下修改Drupal 8的默认输出,语言切换器。理想情况下,我希望能够在枝模板中做到这一点,不必生成 Massive PHP文件,overwwwrites整个链路生成系统并添加一个大如果需要覆盖的情况。 我认为输出布局应该在类似于这个答案(这个答案输出了每种语言的相同URL) 我正在使用引导作为基本...

6  你如何在树枝上打印视图字段?  ( How do you print view fields on twig ) 
我有一个视图并将标题添加为字段。 例如:如何打印标题? 在Drupal 7中,它与一样简单 视图 - 视图 - 字段 - [ViewName] .tpl.php <?php print $fields["title"]->content; ?> 我们如何在drupal 8中这样做? 我已创建视图...

-1  主题重置密码邮件的模板的名称是什么?  ( What is the name of the template to theme a reset password mail ) 
我想主题用于当用户忘记密码时向用户发送链接的邮件。我想知道我需要命名模板文件,以便Drupal将拍摄我的电子邮件模板文件。 我正在使用 mime mail 模块。如何找到特定模块的关键? ...

0  是否可以使用Page Manager和D7中的面板显示EntityForm类型?  ( Is it possible to display entityform types using page manager and panels in d7 ) 
目前,我有一个d7站点,我的主内容区域使用Page Manager和面板变体显示。我创建了一个允许用户请求约会的EntityForm类型,并且我希望此特定的EntityForm类型与默认页面提供不同的布局.TPL.php提供。 我很乐意为所有EntityForm类型提供默认的面板布局,但我似乎无法找到这样做的方法(...

4  是否有等同于template_preprocess_search_results()的东西?  ( Is there something equivalent to template preprocess search results ) 
我刚刚意识到template_preprocess_search_results()函数已在Drupal 8中遗漏出于某些原因,虽然 template_preprocess_search_result() (用于单个结果)仍然存在。 我需要能够在渲染之前操纵搜索结果,因为我将在drupal 7中的 template_...

1  主题形式。形状元素  ( Theming forms form element ) 
请,帮助。是否可能为form-compent.html.twig实现不同的模板? for表单"用户形式" 一个模板,以及其他形式的第二模板。 ...

4  Drupal 8:在Twig模板中渲染一个现场收集项目  ( Drupal 8 render a field collection item in a twig template ) 
在Drupal 8中,我有一个内容类型,它使用这样的现场收集模块: field_body (FieldCollection,可重复) field_image_alignment (布尔) field_picture (图像) field_free_text (长文) 我想主题这个字段。 我...

0  我应该调用一个函数来在自定义内容类型模板中查询数据库吗?  ( Should i call a function to query the database in a custom content type template ) 
我在模板中调用以下函数,以进行自定义内容类型,但我的高级开发人员建议调用模板文件中的函数不是Drupal标准。 function some_function($AA_tid = 0) { $dis_pt = db_select('some_tble', 'v') ->fields('v', arra...

1  如何在页面字段之间插入块内容?  ( How can i insert block content between page fields ) 
我的页面内容类型有两个实体参考类型,引用其他内容类型。 英雄 引用 英雄在页面顶部显示,我希望页面底部的引号。 在这两条内容之间,我有我想要显示的自定义块和视图。 如何在其他自定义内容下有英雄和引号节点? ...

-1  有没有办法将自定义类/包装器添加到页面节点,类似于使用视图创建的页面?  ( Is there a way to add custom classes wrappers to page nodes similar to pages cr ) 
我正在研究设计师提出的5个主题颜色,我需要与特定页面相关联。主题有2个区域需要受主题颜色的影响:侧边栏和内容。 我希望将一个字段添加到基本页面内容类型链接到分类词词汇表,其中术语将是颜色,所以我可以在创建页面时选择主题。我需要将一个类添加一个术语高度,足以影响页面内容类型的所有其他字段。 这将是在视图中的行等级,其中...

0  自定义主题块位置未导入  ( Custom theme block position is not importing ) 
问题: 使用放置在不同区域的块的自定义主题。 使用UI将自定义块放在主题中。 导出配置。 drush cex vcs 当它在新的环境中导入我的配置时,在我的默认配置中存在的单个块的文件,尽管在我的默认配置目录中出现的单个块,但是在适当的区域中未出现的自定义块... 如何导入配置,以便从我的自定义主题中块...

0  在外部jQuery中使用{{twig变量}}  ( Using twig variables inside external jquery ) 
开发D8主题,我正在加载包含一些jQuery代码的外部.js文件(所以它不在枝形模板内)。 是否可以访问和修改外部jQuery内部 $status_definition = DataDefinition::create('list') ->setLabel(new TranslatableMarkup('Sta...




© 2021 it.wenda123.org All Rights Reserved. 问答之家 版权所有


Licensed under cc by-sa 3.0 with attribution required.