Adding Custom Variables to Templates

This is a quick note on how to add custom variables to an overridden template. I need to add some logic on whether or not to display a button: is this video assigned to the user? Okay, then display the button. Previously, I had just added the button to the template, but now that there is more complex logic, I will move it out into a preprocess_node hook in my module.

The template that I have created is for a custom content-type called "video". I have created a new template in my module node--video.tpl.php, and I want to display the button with a simple line of code inside the template:

print $mu_quiz_take_video_quiz_button;

Inside of my module mu_quiz.module I will create a function mu_quiz_preprocess_node that contains the complex logic and returns the button:

* Implements hook_preprocess_node().
function mu_quiz_preprocess_node(&$variables){

  if ($variables['node']->type == 'video') {
    $nid = $variables['node']->nid;
    global $user;

    // check if $nid is assigned here
    if(mu_quiz_lookup_assignment($user->uid, $nid)) {
      // Take quiz Button
      $cs="<div class='conitent clearfix coding-sheet-form'>";
      $cs.="  <form action='/mu-quiz/video-quiz' method='post'>";
      $cs.="    <input type=hidden name='video_id' value='". $nid ."'>";
      $cs.="    <input type='submit' value='Fill out Video Quiz'>";
      $cs.="  </form>";
      $variables['mu_quiz_take_video_quiz_button'] = $cs;

There it is. In a follow-up post I will show how to output the button with a render array.


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.