dongmo20030416 2016-11-17 01:33
浏览 61

将变量传递给_preprocess_node函数以在节点模板中使用

I've been racking my brains over this one but I'll do my best to describe the problem as best as possible. I have a custom function written within template.php, with a bunch of conditionals. When a condition is true, I would like to assign a value to a variable, and then pass that variable intro a node preprocess function that allows that variables to be rendered on a node template.

The function containing the condition:

function _mytheme_date_repeat_string($vars) {

    $exdate_pos = strpos($rrule['WKST'], 'EXDATE:');
    if($exdate_pos > 0) {

        $vars['testvar'] = 'abc123';
    }
 }

The preprocess function that I would like to render the variable in for node template use:

function mytheme_preprocess_node(&$vars, $hook) {

  $vars['new_variable'] = $testvar;

}

Intended usage in node.tpl.php:

<?php print $new_variable; ?>

I'm not great with PHP, but I know enough about programming to know that variable scope might be an issue here. What would be the best way to implement this? Any guidance is greatly appreciated.

Thanks, Mark.

  • 写回答

1条回答 默认 最新

  • dtwzwmv87399 2016-11-17 12:47
    关注

    If it is not called, your _mytheme_date_repeat_string() function will never be executed. Preprocess functions (ie. any function starting mytheme_preprocess_, are called automatically by Drupal's theme system.

    What you need is either move the code of _mytheme_date_repeat_string() in mytheme_preprocess_node() or refactor it and call it.

    function _mytheme_date_repeat_string($rrule) {
        $exdate_pos = strpos($rrule['WKST'], 'EXDATE:');
        if($exdate_pos > 0) {
          return 'abc123';
        }
        else {
          return NULL;
        }
     }
    
    /**
     * Prepares variables for node templates.
     */
    function mytheme_preprocess_node(&$variables, $hook) {
    
      // Get $rrule from somewhere
      $rrule = ... ;
    
      $testvar = _mytheme_date_repeat_string($rrule);
      if ($testvar) {
        $variables['new_variable'] = $testvar;
      }
    }
    

    You code does not show where the $rrule calue comes from. I assume you would get it for $variables['node'].

    评论

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染