2

Is it possible to return an integer in it's text form? I searched the Twig documentation and Stack Overflow and did not find a solution.

I could of course just set it up and create it based on the loop index,

{% if loop.index == '1' %}
{% set place = 'one' %}

but that breaks if the user creates entries above whatever number I set up to so it is not a real solution of any value. I am wondering if someone here might have a solution?

The return would be "one" in place of '1', "two" in place of '2', etc.

Thanks for any help!

2 Answers 2

4

As far as I know there is no convertNumberToWords type method in twig or php. However, you could create your own. This could be done in several ways: twig macro, custom twig filter, or plugin variable.

Here is an example of a simple twig macro that uses a lookup table:

{% macro numberToWords(integer) %}

    {% digits = {
        0:  'zero',
        1:  'one',
        2:  'two',
        3:  'three',
        4:  'four',
        5:  'five',
        6:  'six',
        7:  'seven',
        8:  'eight',
        9:  'nine',
        10: 'ten',
        11: 'eleven',
        12: 'twelve',
        13: 'thirteen',
        14: 'fourteen',
        15: 'fifteen',
        16: 'sixteen',
        17: 'seventeen',
        18: 'eighteen',
        19: 'nineteen',
    } %}

    {{ digits[integer] }}

{% endmacro %}

{% import _self as macros %}

{% for i in 1..19 %}
    {{ macros.numberToWords(loop.index) }}
{% endfor %}

Creating a custom twig filter or a plugin would of course allow you to use php, which might provide a more robust solution. Doing a quick search I see there are a few examples that people have written, like this one.

If you want to do this via a plugin, you might try using lindseydiloreto's excellent craft-businesslogic as a starting point. Then just paste the php methods (from the example linked above) into the variables file (along with any dependency methods).

1
  • Thanks for your answer. I did not want to keep searching if nothing exists so I appreciate you taking the time. I will look into those links! Commented Dec 27, 2016 at 19:11
1

A little bit late to the party, but I recently came across this article on the power of t()

In it he does a bit of magic like this:

{{ 'We are {n,spellout} in line' | t({n: 138}) }} 
en-US => We are one hundred thirty-eight
hu-HU => Százharmincnyolc vagyunk

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.