2016-09-14 83 views
0

我是Drupal的新手,我非常喜欢它。我正在自己学习,但现在我陷入了一个问题。Drupal 8 - 添加类到链接

我创建了一个显示标题和链接列表的自定义块。所以该块中唯一的字段是类型链接。这是我的页脚区域块。所以当用户点击时,它会在新标签中打开一个新网站。

我要改变的HTML输出只是此块类型,所以我拿出这个主题建议: 场 - 块内容 - 现场链接 - 英尺,links.html.twig

我的问题是如何为每个<a>标签添加一个类?

我试过使用模块'链接类'。它的作品越野车。它只会在安装模块之前读取已经存在于css中的类。它不会读取安装模块后创建的新类。我尝试了不同的东西,清除了缓存很多次,但很奇怪。必须有更好的方式来添加没有模块的类。

任何人都可以帮助我,并告诉我添加一个类到我的<a>标签的最佳方式吗?

谢谢:)

下面是

{% if label_hidden %} 
    {% if multiple %} 
    <div{{ attributes }}> 
     {% for item in items %} 
     <div{{ item.attributes }}>{{ item.content }}</div> 
     {% endfor %} 
    </div> 
    {% else %} 
    {% for item in items %} 
    {{ item.content }} -------------> add class here 
    {% endfor %} 
    {% endif %} 
{% else %} 
    <div{{ attributes }}> 
    <div{{ title_attributes }}>{{ label }}</div> 
    {% if multiple %} 
     <div> 
    {% endif %} 
    {% for item in items %} 
     <div{{ item.attributes }}>{{ item.content }}</div> 
    {% endfor %} 
    {% if multiple %} 
     </div> 
    {% endif %} 
    </div> 
{% endif %} 

回答

0

默认模板它取决于你如何建立一个自定义的块。但正如你所说,为了添加一些类而创建一个新模板有点矫枉过正。

因此,这里有关于如何创建一般链接一些很好的答案,以及如何像类属性添加到他们: https://drupal.stackexchange.com/questions/144992/how-do-i-create-a-link

有针对不同情况略有不同的答案,所以看自己是什么适合你案例最好。

3

替换{{item.content}}用硬编码链接:

<a href="{{ item.content['#url']|render }}" {% if item.content['#options']['external'] %} target="_blank" {% endif %} class="some class here">{{ item.content['#title'] }}</a> 

或者,如果你愿意,你可以合并类选项:

{{ item.content|merge({'#options': {'attributes': {'class': ['some', 'class', 'here']}}}) }} 
0

我也有延长链接的麻烦在Drupal 8中。 菜单链接,评论表单链接,Drupal想要渲染系统链接值。

我的尝试通常都是这样的模式: 1.尝试在使用字段时使用字段添加类,并使用枝条覆盖。

  1. 如果这是不可能的,请检查主题钩子,通过属性添加类。 (Chrome Drupal模板助手扩展帮助。)我能够添加一个类到父UL,但不是A的。

  2. 检查树枝模板中的键并显式使用{{var.name [#url]}}。 (引导Drupal主题做这在他们的menu.html.twig!)例:

     a href="{{ item.url }}" class="dropdown-toggle" data-target="#" data-toggle="dropdown">{{ item.title }}
  3. 如果这3次尝试失败...我通过Javascript添加属性。 ('。comment-forbidden')。parent()。addClass('list-unstyled');

我试图类添加到节点链接(登录或注册后发表评论)在node.html.twig并以一个错误被提示:

$variables['content']['links']['#attributes']['class'][] = 'list-unstyled'; 

当#lazy_builder回调指定,不存在任何属性;所有属性必须由#lazy_builder回调生成。您指定了以下属性:#attributes。在Drupal \ Core \ Render \ Renderer-> doRender()

1

对于那些喜欢使用php构造html render元素的人。 一个相当典型的链接:

$elements[$delta] = [ 
    '#type'  => 'link', 
    '#title'  => $value, 
    '#url'  => Url::fromUri('mailto:' . $value), 
    '#attributes' => [ 
     'class' => ['myClass'] 
    ] 
    ];