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>
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!