Hi
Im trying:
function qsysdesktop_preprocess_page(&$variables) {
$variables['inpreprocesspage'] = 'In preprocesspage set by code';

}
in qsysdesktop.theme.
In page.html.twig I am doing:

Set by me:{{inpreprocesspage}}

Does not write output in page (cache cleared and so on, debug on.

How can I accomplish this ?
Thanks for help and info
Michael

Comments

Eyal Shalev’s picture

Can you affect existing variables?

meikidrupal’s picture

function qsysdesktop_preprocess_page(&$variables) {

$variables['title'] = 'My completely new title';

/*
$variables['inpreprocesspage'] = 'In preprocesspage set by code';
*/

}

and in page.html.twig:

Set by me 1:{{title}}

But I am not so sure, what variables i have at my disposition. looked in http://www.drupalcontrib.org/api/drupal/drupal!core!includes!theme.inc/f.... Is this the authoritative reference ?

But since I am basically a MS ASP.NET / Javascript dev, I still dont know my way around in Drupal. And may be I am something fundamentally wrong.

meikidrupal’s picture

Ok so I found out:
if you want a new variable set in a hook one has to take a hook for the same level as the twig template:
f.i.: if you want to have it page.html.twig one has to set it in themename_preprocess_page.

Jeff Burnz’s picture

Remember that output is not automagically sanitised, so you could use a render array and the render key #markup to be sure strings are escaped, e.g.

$variables['inpreprocesspage']['#markup'] = 'In preprocesspage set by code';

otherwise look to use XSS or HTML classes, e.g.

use Drupal\Component\Utility\Xss;
use Drupal\Component\Utility\Html;

I use one of these in my theme, such as $variables['path_info'] = parse_url(Xss::filter($_SERVER['REQUEST_URI']));

lucasvm’s picture

FOR DRUPAL 8

In youtheme.theme file:

Add this fuction:

/**
* Implements hook_preprocess_HOOK() for page.html.twig.
*/
function mytheme_preprocess(&$variables, $hook) {

//Set Variable

$variables['phone'] = '12345';

}

Then in your template:

{{phone}} it will print 12345

allserp243’s picture

Then in your template:

{{phone}} it will print 12345

Mayankkumar Jeshti’s picture

This will create huge performance issue. We can create twig extension to achieve this.

drupalganesh’s picture

I have also used same logic in my code. Can you tell me what performance issues it will create?? And also please tell about twig extension.