I've been looking into the drupal 8 commerce module, I want to take the variable $count that is generated within


and place it into a custom block in my own theme. I see that the build() function returns the count variable through #count which can then be accessed via twig. Just for reference Drupal commerce currently uses the template:


to output the variables and markup:

<div{{ attributes}}>
  <div class="cart-block--summary">
    <a class="cart-block--link__expand" href="{{ url }}">
      <span class="cart-block--summary__icon">{{ icon }}</span>
      <span class="cart-block--summary__count">{{ count_text }}</span>
  {% if content %}
  <div class="cart-block--contents">
    <div class="cart-block--contents__inner">
      <div class="cart-block--contents__items">
        {{ content }}
      <div class="cart-block--contents__links">
        {{ links }}
  {% endif %}

My question is, how I can I make that variable global, are there any implications to just making it global, like what if the user updates the basket?

How do I go about achieving this? Does anyone have a possible solution?

  • 1
    Nothing is "global" in D8. You'll need to tell us where you're planning to use the count, so that we can recommend the best course of action. You'd probably want to copy the logic from CartBlock (get the cart from the cart provider, then count the order items & quantities) Jan 27, 2017 at 13:42
  • I want to insert it into a custom block. Knowing this.. I think like you said... I should just copy the logic as kind of a custom sub module that gathers the particular logic i'm after from the cartblock controller etc.. any other thoughts?
    – cwiggo
    Jan 27, 2017 at 15:46

1 Answer 1


you will have to use hook_preprocess_hook to achieve this by passing the variable to the template.

function template_preprocess_TEMPLATE_NAME(&$variables) {
    $variables['YOUR_VAR_NAME'] = $YOUR_VAR;

Then you can access your var in the template like so:


Your Answer

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

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