0

Can anybody help me to understand what those lines are doing ?

VAR_TOKEN_START = '{{'
VAR_TOKEN_END = '}}'
BLOCK_TOKEN_START = '{%'
BLOCK_TOKEN_END = '%}'
TOK_REGEX = re.compile(r"(%s.*?%s|%s.*?%s)" % (
    VAR_TOKEN_START,
    VAR_TOKEN_END,
    BLOCK_TOKEN_START,
    BLOCK_TOKEN_END
))

TOK_REGEX.split('{% each vars %}<i>{{it}}</i>{% endeach %}')

I don't understand the % on the regex expression. And why we split on TOK_REGEX variable expression.

1

1 Answer 1

1

This part:

TOK_REGEX = re.compile(r"(%s.*?%s|%s.*?%s)" % (
    VAR_TOKEN_START,
    VAR_TOKEN_END,
    BLOCK_TOKEN_START,
    BLOCK_TOKEN_END
))

uses string formatting to build a regex in a more understandable manner than just a jumble of characters. The % operator replaces each %s with the contents of the corresponding string in the following tuple. This allows the author of the code to give meaningful names to the {{, }}, {%, and %} parts of the regex.

The split call:

TOK_REGEX.split('{% each vars %}<i>{{it}}</i>{% endeach %}')

equivalent to the re.split function with the compiled pattern, finds all occurrences of text matching the regex in the argument string and returns a list of the parts divided by the matches - except that since the regex was in a capturing group (the parentheses in the regex string), the regex matches are also included in the list.

Sign up to request clarification or add additional context in comments.

6 Comments

The exact code is on this website : alexmic.net/building-a-template-engine
Shouldn't this be a comment than an answer?
@gat: It answers the question, doesn't it?
@user3453437: Edit the proper code into the question.
Split returns all words whithout the first expression given which is used as a separator ... But on the example, it's return an array with all word are well-separated ... I don't understand why.
|

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.