Adding custom variable to twig's html.html.twig which is not cachable In the html.html.twig file of the theme I'm using, I want to add a custom variable called {{ amount }} 
like: &lt;div&gt;Amount of items in cart: {{ amount }}&lt;/div&gt;

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.
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

&lt;?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' =&gt; array('html')
      )),
  }

  public function session_var($key) {
    return \Session-&gt;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 %}