Drupal文档教程翻译 - 为区块添加基于标题的id属性

logo-drupal-documentation本站原创编译,转载请给面子,尊重劳动果实,欢迎交流指正。

已然这么久、这么久没有做文档翻译了,我自己都有些许感动了。曾经的文档翻译范版,是首先回顾一下上一篇的概要。那么,我们来看下,在去年8月20日的译文中,我们了解了怎样在节点中显示词汇表图片。大半年过去了,Drupal官方文档充实了不少内容,有实用价值的东西蛮多的。今天我们来看怎样基于区块的标题(block title)为该区块添加id属性。

Drupal原生输出的区块(block)会有形如“block-xx-xx”的id属性,实际应用中,我们时常需要按照区块标题的命名方式为其id命名。通过下面的方法,即可轻松实现;轻松熊实现:

首先,我们需要通过预处理函数(preprocess function)来定义相关变量。在当前主题的template.php文件中输入以下代码(记得将“mytheme”前缀替换为当前主题名称):

<?php
/**
 * Override or insert PHPTemplate variables into BLOCK templates.
 *
 * @param $vars
 *   A sequential array of variables to pass to the theme template.
 * @param $hook
 *   The name of the theme function being called ("block" in this case.)
 */
function mytheme_preprocess_block(&$vars, $hook) { //change mytheme to your theme name
  $block = $vars['block'];
 
  // Create css id attribute based on 'Block title' when available.
  if (!empty($block->title)) {
  // Create the variable and ensure that it is correctly formatted with mytheme_id_safe function
  $cssid = mytheme_id_safe($block->title);
  }
  else  {
  // If no "Block title", create css id attribute the traditional way.
  $cssid = "block-$block->module-$block->delta";
  }
  $vars['block_cssid'] = $cssid;
}
/**
 * Converts a string to a suitable html ID attribute.
 *
 * - Preceeds initial numeric with 'n' character.
 * - Replaces space and underscore with dash.
 * - Converts entire string to lowercase.
 * - Works for classes too!
 *
 * @param string $string
 *   The string
 * @return
 *   The converted string
 */
function mytheme_id_safe($string) { //change mytheme to your theme name
  if (is_numeric($string{0})) {
    // If the first character is numeric, add 'n' in front
    $string = 'n'. $string;
  }
  return strtolower(preg_replace('/[^a-zA-Z0-9-]+/', '-', $string));
}
?> /* exclude this closing php tag in your template.php file */

其中的“$block_cssid”就是用来输出id名称的变量。

接下来,在block.tpl.php模板文件中输出该变量:

<div id="<?php print $block_cssid; ?>" class="block block-<?php print $block->module ?>">
<?php if ($block->subject): ?>
  <h2><?php print $block->subject ?></h2>
<?php endif;?>
 
  <div class="content">
    <?php print $block->content ?>
  </div>
</div>

搞定。

几点需要注意:

  • 前面代码中的mytheme_id_safe($string)函数已经可以帮助我们确保输出的id属性不会以数字开头
  • 如果当前主题的template.php文件中已经存在区块的预处理函数,那么不需要另外添加新的function mytheme_preprocess_block
  • 如果当前主题中还没有block.tpl.php模板文件,那么需要从站点根路径的modules/system文件夹中复制一份,放到当前主题路径中,在该文件中进行修改覆写。
  • 本文中的方法会作用于所有的区块;如果需要在特定的页面中实用,需要使用模板建议(template suggestions,详见“Drupal文档教程翻译 - 覆写输出 - template suggestion(1)”)

 

译者:Viiiix7210
如需转载,请注明官方英文文档及本人译文的出处,谢谢。查看英文原文: How to display some arbitrary HTML on a specific page based on the URL you are on
译者:Viiiix7210
如需转载,请注明官方英文文档及本人译文的出处,谢谢。查看英文原文: Create block id attributes based on block title

 


收藏与分享