<s> from django import template <EOL> from django . template . base import TemplateSyntaxError <EOL> from django . utils . html import conditional_escape <EOL> from django . utils . safestring import mark_safe <EOL> from . . models import get_cached_snippet , Snippet <EOL> register = template . Library ( ) <EOL> def build_options ( bits , tag_name ) : <EOL> """<STR_LIT>""" <EOL> options = { } <EOL> for bit in bits : <EOL> try : <EOL> option , val = bit . split ( '<STR_LIT:=>' ) <EOL> except ValueError : <EOL> raise TemplateSyntaxError ( "<STR_LIT>" % tag_name ) <EOL> if option == '<STR_LIT>' : <EOL> option = '<STR_LIT>' <EOL> if option not in [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] : <EOL> raise TemplateSyntaxError ( "<STR_LIT>" % tag_name ) <EOL> options . update ( { option : val } ) <EOL> return options <EOL> @ register . tag <EOL> def snippet ( parser , token ) : <EOL> """<STR_LIT>""" <EOL> nodelist = parser . parse ( ( '<STR_LIT>' , ) ) <EOL> parser . delete_first_token ( ) <EOL> bits = token . split_contents ( ) <EOL> tag_name = bits [ <NUM_LIT:0> ] <EOL> try : <EOL> key = bits [ <NUM_LIT:1> ] <EOL> except IndexError : <EOL> raise TemplateSyntaxError ( "<STR_LIT>" % tag_name ) <EOL> options = build_options ( bits [ <NUM_LIT:2> : ] , tag_name ) <EOL> return SnippetNode ( nodelist , key , ** options ) <EOL> class SnippetNode ( template . Node ) : <EOL> safe = None <EOL> template = None <EOL> language = None <EOL> def __init__ ( self , nodelist , key , ** options ) : <EOL> self . nodelist = nodelist <EOL> self . key = template . Variable ( key ) <EOL> for k , v in options . items ( ) : <EOL> setattr ( self , k , template . Variable ( v ) ) <EOL> def render ( self , context ) : <EOL> key = self . key . resolve ( context ) <EOL> if self . language : <EOL> language = self . language . resolve ( context ) <EOL> else : <EOL> language = context . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> snippet = get_cached_snippet ( key , language ) <EOL> if snippet is None : <EOL> output = self . nodelist . render ( context ) <EOL> snippet = Snippet ( key = key , text = output ) <EOL> snippet . save ( ) <EOL> return output <EOL> if self . template : <EOL> self . template = self . template . resolve ( context ) <EOL> if self . safe : <EOL> self . safe = self . safe . resolve ( context ) <EOL> if self . template : <EOL> if self . safe : <EOL> old_autoescape = context . autoescape <EOL> context . autoescape = False <EOL> rendered = template . Template ( snippet ) . render ( context ) <EOL> context . autoescape = old_autoescape <EOL> return mark_safe ( rendered ) <EOL> return template . Template ( snippet ) . render ( context ) <EOL> if self . safe : <EOL> return mark_safe ( snippet ) <EOL> return conditional_escape ( snippet ) </s>
