php
  • css
  • drupal
  • drupal-6
  • drupal-blocks
  • 2012-12-13 28 views 2 likes 
    2

    我在drupal 6中用php代碼封鎖了一個塊,我想添加一個類到body,但是我怎麼能做到這一點?如何使用php在drupal 6的塊中添加一個body類?

    甚至可以在預處理函數之外做到這一點?

    顯示以下PHP代碼是否返回TRUE(PHP模式,僅限專家)。

    <?php 
    $url = request_uri(); 
    if (strpos($url, "somestring")) 
    { 
        $vars['body_classes'] .= ' someclass'; 
    } 
    elseif (arg(0) != 'node' || !is_numeric(arg(1))) 
    { 
        return FALSE; 
    } 
    
    $temp_node = node_load(arg(1)); 
    $url = request_uri(); 
    
    if ($temp_node->type == 'type' || strpos($url, "somestring")) 
    { 
        return TRUE; 
    } 
    ?> 
    
    +0

    使用jquery jQuery('body')。addClass('test'); – softsdev

    +0

    我當然不想用jQuery來做這件事... – Alex

    +2

    爲什麼你想在一個塊中做這個,而不是template_preprocess_page? (http://api.drupal.org/api/drupal/includes!theme.inc/function/template_preprocess_page/6) –

    回答

    3

    前期備註:如果你的實際情況取決於請求URL,因爲你的例子顯示,然後我跟特里Seidlers評論同意你剛纔應該在自定義做一個*_preprocess_page()實現中模塊或在您的主題template.php

    更通用的選項:

    AFAIK,這是不是從一個*_preprocess_page()功能之外可以開箱即用。然而,你可以很容易地與助手功能添加此功能:

    /** 
    * Add a class to the body element (preventing duplicates) 
    * NOTE: This function works similar to drupal_add_css/js, in that it 'collects' classes within a static cache, 
    * adding them to the page template variables later on via yourModule_preprocess_page(). 
    * This implies that one can not reliably use it to add body classes from within other 
    * preprocess_page implementations, as they might get called later in the preprocessing! 
    * 
    * @param string $class 
    * The class to add. 
    * @return array 
    * The classes from the static cache added so far. 
    */ 
    function yourModule_add_body_class($class = NULL) { 
        static $classes; 
        if (!isset($classes)) { 
        $classes = array(); 
        } 
        if (isset($class) && !in_array($class, $classes)) { 
        $classes[] = $class; 
        } 
    
        return $classes; 
    } 
    

    這允許你「收集」從PHP代碼中的任意體類在頁面週期的任何地方,只要它被稱爲最後一頁預處理之前。類值存儲的靜態數組中,實際除了輸出發生在yourModule_preprocess_page()實現:

    /** 
    * Implementation of preprocess_page() 
    * 
    * @param array $variables 
    */ 
    function yourModule_preprocess_page(&$variables) { 
        // Add additional body classes, preventing duplicates 
        $existing_classes = explode(' ', $variables['body_classes']); 
        $combined_classes = array_merge($existing_classes, yourModule_add_body_class()); 
        $variables['body_classes'] = implode(' ', array_unique($combined_classes)); 
    } 
    

    我通常做這從一個自定義模塊內,但你可以一個主題模板中做同樣的。 PHP文件。

    使用此功能,您幾乎可以在任何地方執行以下操作,例如:塊組裝時:

    if ($someCondition) { 
        yourModule_add_body_class('someBodyClass'); 
    } 
    
    相關問題