0

i build a macro that contains a function. The function basically crop a text without catting words. My problem is how to call that twig macro if it is in different folder. if it is i same folder its easy. i just import the twig name. {% import 'croptext.twig' as cropText %} But since this file contains a useful function all templates will call it so its better to put it in special folder like "tool" or "filter". But i still have any way to call it any help ?

{% macro crop_text(text, len) %}
  {% if text | length < len %}
    {{ text }}
  {% else %}
    {% set break = false %}
    {% set croppedParagraph = '' %}
    {% set paragraph = text | split(' ') %}
    {% set totalLength = 0 %}
    {% for word in paragraph  if not break %}
        {% if totalLength >= len %}
          {% set break = true %}
        {% else %}
          {% set totalLength = totalLength + 1 +  word | length %}
          {% set croppedParagraph = croppedParagraph ~ ' ' ~  word %}
       {% endif %}
    {% endfor %}
    {{ croppedParagraph ~ ' ...' }}
 {% endif %}

{% endmacro %}

The function is working. I think its better to share more code to have a better idea about what i am doing. this is my project structure.enter image description here

1 Answer 1

3

You can call the macro by:

  1. In the same twig Using _self:
    From Documentation:

    It's possible to place the macro within the same twig from which you call it. The _self context is used in this case...

{{ _self.crop_text(text, len) }}

  1. From External File using import :
    Like the following:
    Just move your croptext.twig into yourtheme/templates folder and then you can use the following call in any twig:

{% import '@yourtheme/croptext.twig' as cropText %}

For more information take a look at Macros in Twig Templates documentation.

3
  • 1
    you can also do it the drupal 8 module way .. youtube.com/watch?v=9PeAfExNSDk
    – taggartJ
    Commented Jan 29, 2019 at 3:57
  • thanks @berramou can i replaced to tool to better structure folder ? since this function its not really html template but a function that process a text ? Commented Jan 30, 2019 at 15:47
  • Taggart, i am decoupled from drupal as FE i have only twig. and local server form pattern-lab to render pages locally. Commented Jan 30, 2019 at 15:48

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.