1

I have next to no experience with php as a language, and am running it a little problem in producing a Drupal theme. What I need is to execute a function once, that will return a Boolean, then use that Boolean throughout the template.

Here is what I have so far:

html.tpl.php->

<?php 

   function testMobile(){
       return false;
   }

   define('isMobile', testMobile());

?>

...

<?php 
    if(!isMobile){
        echo '<h1>NOT MOBILE</h1>';
    }else{
        echo '<h1>IS MOBILE</h1>';
    }
?>

page.tpl.php->

<?php 
   if(!isMobile){
       echo '<h1>IS DESKTOP</h1>';
   }else{
       echo '<h1>NOT DESKTOP</h1>';
   }
?>

In the drupal output I get this ->

NOT MOBILE

NOT DESKTOP

along with this error message:

Notice: Use of undefined constant isMobile - assumed 'isMobile' in include() (line 77 of /Users/#/#/#/sites/all/themes/#/templates/page.tpl.php).

what am I doing wrong here? How can I most easily achieve my goal?

2 Answers 2

3

It seems that the defined variable is falling out of the scope of the template file. You can simply solve this by using a session variable.

Below is a code sample ...

session_start(); // not necessary with drupal
$_SESSION['isMobile'] = testMobile();

function testMobile(){
   return false;
}

In your template you can add following...

<?php 
   if(!$_SESSION['isMobile']){
       echo '<h1>IS DESKTOP</h1>';
   }else{
       echo '<h1>NOT DESKTOP</h1>';
   }
?>
Sign up to request clarification or add additional context in comments.

Comments

0

Try to define variable in template.php in hook_theme_preprocess_page(&$vars, $hook).

So template.php can looks follow way:

function testMobile(){
  return false;
}

function YOURTHEME_theme_preprocess_page(&$vars, $hook) {
  $vars['isMobile'] = testMobile();
}

And page.tpl.php

<?php 
   if(!$isMobile){
       echo '<h1>IS DESKTOP</h1>';
   }else{
       echo '<h1>NOT DESKTOP</h1>';
   }
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.