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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化