2

In the html.html.twig file of the theme I'm using, I want to add a custom variable called {{ amount }} like: <div>Amount of items in cart: {{ amount }}</div>

And I want it to be (in php): count($_SESSION['cart']).

If I add this to my custom module's hook_preprocess(_html) function:

$variables['cart'] = count($_SESSION['cart']);

Then it will work when I clear the cache, and then it will remember the value. So let's say there are 3 items in cart (variable $_SESSION['cart']), then it shows 3. If I then add one more, then next time I refresh the page, it shows 3 again, but it should say 4!! If I clear the cache, then it says 4! How can I make it "dynamic" without clearing the cache all the time.

  • 1
    You need to write an extension, or do a workaround see here stackoverflow.com/questions/8399389/… – rémy Jul 23 '16 at 23:01
  • Thank you for the link, I tried all the examples, and couldn't make it work. I used a whole day for a simple thing like this, and still on the bottom. I am very new to drupal 8, and still don't get how I can "auto-run" a public function in a controller on each page-reload. I tried all the different solutions, and was happy for the twig_extension, but couldn't make it work. One solution said:#in a controller add -> $twig = new Twig_Environment(...); $twig->addGlobal('session', $_SESSION); I don't even know what controller it is, or what ... means ? – Raf A. Jul 24 '16 at 10:13
1

Ok - so to write your own extension see this answer, refeer to the twig tweak module. Or follow this article, that's it's content adapted to session (using a funcition) - like twig tweak, but different form the linked answer:

In this exemple, we built an extension du display a Drupal block directly from a twig template :

{{ session_var('my_var_name') }}

To to it, you must create a custom Drupal module. You can use the Drupal console to easily create your module.

In your module folder, frist create a new class in in a src subfolder :

For exemple : src/MyTwigExtension.php

<?php
namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'session_var';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('session_var', 
        array($this, 'session_var'),
        array('is_safe' => array('html')
      )),
  }

  public function session_var($key) {
    return \Session->get($key);
  }

}

In a second time you must register your extension as service :

Create a service configuration file

# src/MyTwigModule.services.yml
services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }

And you are done :-)

You can now enable your module and use your Twig extension.


The simple workaround could look like this in twig:

{% app.session.get('cart')|length %}
  • Thank you! I made it work from the bits of pieces of different code. I used this one in the TwigExtension class: public function getGlobals() { $session = new Session(); return array( 'session' => $session->all(), ); } so in html.html.twig I used {{ session.cart|length }} Though I still had to clear cache with drush cr, because it doesn't give you the current value, but the cached value. It's weird since, debug:true, auto_reload:true, cache:false in services.yml. But found this drupal.org/node/2598914 - but it's still weird. – Raf A. Jul 26 '16 at 4:26
  • does it also work with enabled twig cache ? in your production you should not disable the twig cache !!! – rémy Jul 26 '16 at 8:59
  • Well, it doesnt work on my dev, but it works online. So there must be some weird setting I'm not aware of. It doesn't matter, as long as it works on production, then I'm happy. The twig cache is on there, but locally sucks. I'll figure it out, it's not so important. Thanks for helping out. – Raf A. Jul 28 '16 at 4:30
  • It was the devel module that somehow ruined everything. So when I uninstalled it, it worked fine. – Raf A. Jul 28 '16 at 4:40
  • ok - interesting, thx for the update – rémy Jul 29 '16 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.