Search code examples
pythontemplatingcookiecutter

How do I enforce a project to always wrap certain tags with {% raw %} and {% endraw %}?


I am creating template starters that will work with cookiecutter, a python library.

So inside some of the subfolders of a project, for files of a particular type, usually .html, I need any tags that look like this

{% if blah blah %}

to be wrapped like this

{% raw %}{% if blah blah %}{% endraw %}

The exact tags are uncertain.

They may be

{% load blah %}

or

{% include blah %}

or even an image tag

<img class="mx-auto h-12 w-auto" src="{% raw %}{% static 'assets/v-sq.svg' %}{% endraw %}" >

I am unsure how to enforce this or autoformat.

Can advise?

Context about escaping special characters in Cookiecutter

https://cookiecutter.readthedocs.io/en/1.7.2/troubleshooting.html#i-m-having-trouble-generating-jinja-templates-from-jinja-templates


Solution

  • With the help of ChatGPT3 and some googling to find this SO answer

    
    import re
    
    # Open the file in read mode
    with open('file.html', 'r') as file:
        # Read the contents of the file
        text = file.read()
    
    # Use regex to replace all occurrences of the word "apple" (case-insensitive) with "[apple]"
    text = re.sub(r'({\% [^%]+ \%})', '{% raw %}\g<1>{% endraw %}', text, flags=re.IGNORECASE)
    
    # Open the file in write mode
    with open('file.html', 'w') as file:
        # Write the modified content to the file
        file.write(text)