douya2006 2019-07-04 08:33
浏览 118
已采纳

如何在菜单链接中添加img标签?

Please help me with my problem. I have a table in database with mlid (menu link id) column and path column - every primary link menu has an image. I created my custom module which adds a file upload field to menu link edit form, and saves its mlid (menu link id) and path (path to image) to database.

My question is: how can I display my images in my menu items? I want just to add a <img src=".."> tag for every menu item. Code:

<ul class="menu">
  <li>
    <a>First menu item</a>
    // <img>HERE I WISH TO GENEARATE AN IMG TAG</img>
  </li>
  <li>
    <a>Second menu item</a>
    // <img>HERE I WISH TO GENEARATE AN IMG TAG</img>
  </li>
...
</ul>

Please help.

  • 写回答

1条回答 默认 最新

  • duanshai4484 2019-07-04 10:43
    关注

    You can implement a preprocess hook in your module in order to load the image path into the $variables array that is passed to the template :

    function MODULE_preprocess_menu_link(&$variables) {
      $element = &$variables['element'];
      $mlid = $element['#original_link']['mlid'];
    
      # Retrieve image source (if any) from database/original_link object.
      $element['image_src'] = _your_helper_function($mlid);
    }
    

    Then you just need to override the template function so that it outputs the tag according to whether or not an image source has been set.

    In your theme's template.php, create your own THEME_menu_link() function (or if it's already overridden by your current theme, carefully add the logic into the existing one) - for example, the following overrides the default implementation for the Main menu) :

    function THEME_menu_link__main_menu($variables) {
      $element = $variables['element'];
      $sub_menu = '';
    
      if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
      }
    
      $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    
      if (!empty($element['image_path'])) {
        $output .= '<img src="' . $element['image_path'] . '" />';
      }
    
      return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用