0

I'm attempting to use an if statement to determine the value of a field and print a class based on that value. I'm not getting any errors, but the addClass is not working. No classes are being added. I'm assuming it's a simple syntax error. I'm a designer first, and I'm new to Twig templating. Thank you in advance!

{% for key, item in content.field_stat_value if key|first != '#' %}
    <div class="stat-column">
        <div 
        {% if content.field_special_character[key] == '%' %}
          {{ attributes.addClass('percent') }}
        {% elseif content.field_special_character[key] == '$' %}
          {{ attributes.addClass('dollar') }}
        {% endif %}
        class="stat counter" data-count="{{ content.field_stat_value[key] }}">0</div>
        <div class="title">{{ content.field_stat_title[key] }}</div>
        <div>{{content.field_special_character[key]}}</div>
    </div>
  {% endfor %}
4
  • 1
    IMO this is so much easier to do in preprocess instead of add a lot of conditional logic to twig files trying to read from render arrays.
    – Kevin
    Feb 15, 2019 at 16:24
  • @Kevin That sounds great, but I have very limited experience with writing preprocess statements. Any recommendations on how to do so, or good places to learn?
    – Kellen
    Feb 15, 2019 at 17:08
  • 1
    Any luck on this? Just looking at the code above, attributes.addClass('percent') is correct. So either your template isn't loading, or those if checks are evaluating to null, or at least not %/$. Try adding the classes without the if check. If that prints the class at least you know to look at your {% if content.field_special_character[key] == '%' %} statements. Feb 20, 2019 at 16:01
  • @Prestosaurus I actually found an easier way to accomplish what I needed. There was no logic needed! I just injected the raw field value as the class value.
    – Kellen
    Feb 21, 2019 at 17:26

2 Answers 2

1

1) Install and enable the Devel module.

2) Add your /sites/development.services.yml:

# Local development services.
#
# Place this file in the /sites/ directory.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    # Twig debugging:
    #
    # When debugging is enabled:
    # - The markup of each Twig template is surrounded by HTML comments that
    #   contain theming information, such as template file name suggestions.
    # - Note that this debugging markup will cause automated tests that directly
    #   check rendered HTML to fail. When running automated tests, 'debug'
    #   should be set to FALSE.
    # - The dump() function can be used in Twig templates to output information
    #   about template variables.
    # - Twig templates are automatically recompiled whenever the source code
    #   changes (see auto_reload below).
    #
    # For more information about debugging Twig templates, see
    # https://www.drupal.org/node/1906392.
    #
    # Not recommended in production environments
    # @default false
    debug: true
    # Twig auto-reload:
    #
    # Automatically recompile Twig templates whenever the source code changes.
    # If you don't provide a value for auto_reload, it will be determined
    # based on the value of debug.
    #
    # Not recommended in production environments
    # @default null
    auto_reload: auto_reload
    # Twig cache:
    #
    # By default, Twig templates will be compiled and stored in the filesystem
    # to increase performance. Disabling the Twig cache will recompile the
    # templates from source each time they are used. In most cases the
    # auto_reload setting above should be enabled rather than disabling the
    # Twig cache.
    #
    # Not recommended in production environments
    # @default true
    cache: false

3) Add your /sites/default/settings.local.php:

<?php
/**
 * @file
 * Local development override configuration feature.
 *
 * Place this file in the /sites/default/ directory next to settings.php.
 * This will include the development.services.yml file for twig debug use.
 *
 */
assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();

$config['system.logging']['error_level'] = 'verbose';
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$settings['rebuild_access'] = TRUE;
$settings['skip_permissions_hardening'] = TRUE;
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

4) Update your /sites/default/settings.php:

(uncomment this section)

# if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
#   include $app_root . '/' . $site_path . '/settings.local.php';
# }

This will allow you to add {{ dump(content.field_name | keys) }} to your template file so you can see just what keys you need to access the correct values.

Try:

{% for key, item in content.field_stat_value %}
  <pre>
    {{ dump(content.field_special_character | keys) }}
  </pre>
{% endfor %}

Then just add what you need to follow:

{% for key, item in content.field_stat_value %}
  <pre>
    {{ dump(content.field_special_character.mynextkey.0.whatever | keys) }}
  </pre>
{% endfor %}

I add this answer as being able to print out values will help a designer best. Plus, if your class is not printing, I just think content.field_special_character[key] is not evalutaing to %.

Having debug setup will also allow you to ensure you have the correct naming conventions for your twig template.

0

Try the following code:

{% for key, item in content.field_stat_value if key|first != '#' %}
<div class="stat-column">
  {% if content.field_special_character[key] == '%' %}
    {% set attributes = attributes.addClass('percent') %}
  {% elseif content.field_special_character[key] == '$' %}
    {% set attributes = attributes.addClass('dollar') %}
  {% endif %}
    <div {{ attributes.addClass('stat counter').setAttribute('data-count', content.field_stat_value[key]) }}>
      0
    </div>
    <div class="title">{{ content.field_stat_title[key] }}</div>
    <div>{{content.field_special_character[key]}}</div>
</div>
{% endfor %}

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.