【问题标题】:How do you update class and id tags in Drupal 8?你如何更新 Drupal 8 中的 class 和 id 标签?
【发布时间】:2018-10-21 23:50:56
【问题描述】:

有没有办法在 Drupal 中更改或添加类/id 标签到项目?例如,我想更改一组图像,但所有图像上唯一列出的类是“img-responsive”。

我是 Drupal 的新手,我试图在非常有限的时间内自学一切。所以如果你回答,请提供清晰的方向/提供新手可以理解的截图!我非常感谢任何指导或指导我可能的后续步骤。

【问题讨论】:

    标签: drupal drupal-8


    【解决方案1】:

    这是一个绝对过于宽泛的问题。您应该先花时间自学 Drupal 的主题系统及其预处理钩子。

    Working With Twig Templates 开始,它将教您如何创建自定义模板并根据您的需要更改标记或属性(类、ID 等)。

    下次结帐Preprocessing and modifying attributes in a .theme file。假设您已经创建了自定义主题或子主题。您可以使用一些钩子以编程方式更改某些元素的类。


    img-responsive 告诉我你正在使用一些使用 CSS 框架的主题。希望您已经创建了自己的子主题。然后您可以在您的模块.theme 文件中添加类似以下内容。

    要将类直接添加到<img> 标签,您可以通过其图像样式来识别它:

    /**
     * Implements template_preprocess_image().
     */
    function MYTHEME_preprocess_image(&$variables) {
    
      // Check the image style.
      if ($variables['style_name'] == 'img_fluid') {
    
        // Add class.
        $variables['attributes']['class'][] = 'img-fluid';
      }
    }
    

    如果您想将类添加到图像字段(包装容器),您可以通过名称来定位字段:

    /**
     * Implements template_preprocess_field().
     */
    function MYTHEME_preprocess_field(&$variables) {
    
      // Check for your image field.
      if ($variables['element']['#field_name'] == 'field_MYIMAGE') {
    
        // Add class.
        $variables['attributes']['class'][] = 'img-fluid';
      }
    }
    

    来源:How to add a class to the image tag in field.html.twig?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-23
      • 2017-05-20
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多