Coverage for documents/templating/utils.py: 75%

8 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-10 09:07 +0000

1import re 

2 

3 

4def convert_format_str_to_template_format(old_format: str) -> str: 

5 """ 

6 Converts old Python string format (with {}) to Jinja2 template style (with {{ }}), 

7 while ignoring existing {{ ... }} placeholders. 

8 

9 :param old_format: The old style format string (e.g., "{title} by {author}") 

10 :return: Converted string in Django Template style (e.g., "{{ title }} by {{ author }}") 

11 """ 

12 

13 # Step 1: Match placeholders with single curly braces but not those with double braces 

14 pattern = r"(?<!\{)\{(\w*)\}(?!\})" # Matches {var} but not {{var}} 

15 

16 # Step 2: Replace the placeholders with {{ var }} or {{ }} 

17 def replace_with_django(match): 

18 variable = match.group(1) # The variable inside the braces 

19 return f"{{{{ {variable} }}}}" # Convert to {{ variable }} 

20 

21 # Apply the substitution 

22 converted_format = re.sub(pattern, replace_with_django, old_format) 

23 

24 return converted_format