Skip to content

Commit

Permalink
Add support for raw/verbatim blocks in Jinja/Twig
Browse files Browse the repository at this point in the history
Jinja provides a `raw` tag and Twig provides a `raw` tag in its
1.x version and a `verbatim` one in newer versions.

To make the code simple, since the Twig lexer extends from the Jinja
one, the latter holds the logic for both tags.
  • Loading branch information
robin850 committed Jun 8, 2019
1 parent c2daa8d commit 3c55915
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
28 changes: 27 additions & 1 deletion lib/rouge/lexers/jinja.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ def self.pseudo_keywords
@@pseudo_keywords ||= %w(true false none True False None)
end

def self.raw_keywords
@@raw_keywords ||= %w(raw verbatim)
end

def self.word_operators
@@word_operators ||= %w(is in and or not)
end
Expand Down Expand Up @@ -113,7 +117,10 @@ def self.word_operators

state :statement do
rule /(\w+\.?)/ do |m|
if self.class.keywords.include?(m[0])
if self.class.raw_keywords.include?(m[0])
token Keyword
goto :raw
elsif self.class.keywords.include?(m[0])
groups Keyword
elsif self.class.pseudo_keywords.include?(m[0])
groups Keyword::Pseudo
Expand All @@ -133,6 +140,25 @@ def self.word_operators

rule /\%\}/, Comment::Preproc, :pop!
end

state :raw do
mixin :text

rule /\%\}/ do
token Comment::Preproc
push :raw_block
end
end

state :raw_block do
rule %r{(\{\%)(\s+)(endverbatim|endraw)(\s+)(\%\})} do
groups Comment::Preproc, Text::Whitespace, Keyword, Text::Whitespace,
Comment::Preproc
pop!(2)
end

rule /(.+?)/, Text
end
end
end
end
8 changes: 8 additions & 0 deletions spec/visual/samples/jinja
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,12 @@ Hello {{ user.name|capitalize }} !
{# A comment on multiple lines
to hide a piece of code or whatever #}

{% raw %}
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
{% endraw %}

{% raw %} One line {{ raw }} block {% endraw %}

{% include 'footer.html' %}
8 changes: 8 additions & 0 deletions spec/visual/samples/twig
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,12 @@
{% flush %}
{% endif %}

{% verbatim %}
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
{% endverbatim %}

{% verbatim %} One line {{ verbatim }} block {% endverbatim %}

{% include 'footer.html' %}

0 comments on commit 3c55915

Please sign in to comment.