0

I have a variable whose value is say FileSystem, I would like to get this printed as file_system in my template.
Observe I am doing 2 things here:
1. If the first letter of my string is capital letter then I am converting it to lower
2. If any of my other letters is in caps, then I am replacing it with underscore followed by its lower string format.
One more example would be converting StackOverFlow to stack_over_flow How can I get this done?

1 Answer 1

1

You could write a custom jinja filter that takes your variable as input and allows you to apply your desired transformation.

Quoted from the official jinja help:

Custom filters are just regular Python functions that take the left side of the filter as first argument and the arguments passed to the filter as extra arguments or keyword arguments.

jinja help section for custom filters

Example:

def convert_to_snakecase(value):
    # convert your value here (lower case first letter + snake case)
    return formatted_value

Register your custom filter:

app.jinja_env.filters['convert_to_snakecase'] = convert_to_snakecase

Call your filter inside the template:

{{ my_variable|convert_to_snakecase }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.