CMS Development

MvdLanden
Participant

Using a variable inside range()

SOLVE

Hi all,

 

I'm trying to create a custom module which enables me to use an editable text field to modify a variable to use in an options variable in order to make repeatable blocks.

 

I have a text field named widget.repeats which has a default value of 5, but could be anything. I'm storing this by using this variable:

 

{% set repeats = widget.repeats %}

Next I have another variable which I'm going to use to loop through:

 

{% set my_options = range(1, repeats) %} // Not working, should output range(1, 5)
{% set my_options = range(1, {{repeats}}) %} // Not working, should output range(1, 5)

However these variables throw an error. How am I supposed to make this work? When I get this to work I could do something like:

 

{% for options in my_options %}
{% if loop.index <= widget.repeats %}
// Repeat this {% endif %} {% endfor %}

 Thanks in advance!

0 Upvotes
1 Accepted solution
Jsum
Solution
Key Advisor

Using a variable inside range()

SOLVE

@MvdLanden

 

I didn't have an issue getting this to work:

{% set test2 = [1,2,3,4,5,6,8,9,0] %}
        
{% set test3 = 9 %}
        
{% set range1 = range(2, test3, 2) %}
        
{% for items in range1 %}
        
        "boom"
        
{% endfor %}

I used test3 to simulate a choice from my test2 list. I set test3 as the stop for the range the for loop started at position 2, stopped at position 9, and stepped by 2 positions.

 

Your issue is most likely that because you are using a text input to capture the desired number, the number is coming in as string not an int. filter it as an int:

{% text "my_text" value='25', export_to_template_context=True %} 
{{ widget_data.my_text.value|int + 28 }}

equals 53

View solution in original post

2 Replies 2
Jsum
Solution
Key Advisor

Using a variable inside range()

SOLVE

@MvdLanden

 

I didn't have an issue getting this to work:

{% set test2 = [1,2,3,4,5,6,8,9,0] %}
        
{% set test3 = 9 %}
        
{% set range1 = range(2, test3, 2) %}
        
{% for items in range1 %}
        
        "boom"
        
{% endfor %}

I used test3 to simulate a choice from my test2 list. I set test3 as the stop for the range the for loop started at position 2, stopped at position 9, and stepped by 2 positions.

 

Your issue is most likely that because you are using a text input to capture the desired number, the number is coming in as string not an int. filter it as an int:

{% text "my_text" value='25', export_to_template_context=True %} 
{{ widget_data.my_text.value|int + 28 }}

equals 53

MvdLanden
Participant

Using a variable inside range()

SOLVE

Adding the int filter did the trick. Big thanks!

0 Upvotes