使用hook_view()显示笑话妙语

老葛的Drupal培训班 Think in Drupal

现在你有了一个完整的系统,可以用来输入和编辑笑话。然而,尽管可以在节点提交表单中输入笑话妙语,但在查看笑话时,你却没有提供显示笑话妙语字段的方式,你的用户将会为此感到很困惑。让我们使用hook_view()来显示笑话妙语:
 
/**
 * Implementation of hook_view().
 */
function joke_view($node, $teaser = FALSE, $page = FALSE) {
    // If $teaser is FALSE, the entire node is being displayed.
    if (!$teaser) {
        // Use Drupal's default node view.
        $node = node_prepare($node, $teaser);
 
        // Add a random number of Ha's to simulate a laugh track.
        $node->guffaw = str_repeat(t('Ha!'), mt_rand(0, 10));
 
        // Now add the punch line.
        $node->content['punchline'] = array(
            '#value' => theme('joke_punchline', $node),
            '#weight' => 2
        );
    }
 
    // If $teaser is TRUE, node is being displayed as a teaser,
    // such as on a node listing page. We omit the punch line in this case.
    if ($teaser) {
        // Use Drupal's default node view.
        $node = node_prepare($node, $teaser);
    }
 
    return $node;
}
 
    在这段代码中,如果节点没有被显示为摘要形式(也就是说,$teaser为FALSE),那么笑话中就会包含笑话妙语。你已将笑话妙语的显示分解为一个单独的主题函数,这样就可以方便的进行覆写了。如果一个系统管理员想使用你的模块,但又想自定义外观的话,那么这将会非常方便。通过实现hook_theme(),并提供一个joke_punchline主题函数的默认实现,这样你就告诉了Drupal,你要使用这个主题函数了。
 
/**
 * Implementation of hook_theme().
 * We declare joke_punchline so Drupal will look for a function
 * named theme_joke_punchline().
 */
function joke_theme() {
    return array(
        'joke_punchline' => array(
            'arguments' => array('node'),
        ),
    );
}
 
function theme_joke_punchline($node) {
    $output = '<div class="joke-punchline">'.
        check_markup($node->punchline). '</div><br />';
    $output .= '<div class="joke-guffaw">'.
        $node->guffaw .'</div>';
    return $output;
}
 

Drupal版本: