o
    r|a@                     @   s   d Z ddlmZ ddlmZmZmZ ddlmZm	Z	 ddl
mZ ddlmZ ddlmZmZ ddlmZ dd	lmZ G d
d deZdS )z=
This module provides a Renderer class to render templates.

    )defaults)TemplateNotFoundErrorMissingTags	is_string)ContextStackKeyNotFoundError)Loader)ParsedTemplate)context_getRenderEngine)
SpecLoader)TemplateSpecc                   @   s   e Zd ZdZ								d-ddZedd Zdd Zd	d
 Zdd Z	dd Z
d.ddZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, ZdS )/Renderera  
    A class for rendering mustache templates.

    This class supports several rendering options which are described in
    the constructor's docstring.  Other behavior can be customized by
    subclassing this class.

    For example, one can pass a string-string dictionary to the constructor
    to bypass loading partials from the file system:

    >>> partials = {'partial': 'Hello, {{thing}}!'}
    >>> renderer = Renderer(partials=partials)
    >>> # We apply print to make the test work in Python 3 after 2to3.
    >>> print(renderer.render('{{>partial}}', {'thing': 'world'}))
    Hello, world!

    To customize string coercion (e.g. to render False values as ''), one can
    subclass this class.  For example:

        class MyRenderer(Renderer):
            def str_coerce(self, val):
                if not val:
                    return ''
                else:
                    return str(val)

    Nc	           	      C   s   |du rt j}|du rt j}|du rt j}|du rt j}|du r#t j}|du r*t j}|du r1t j}t|t	r9|g}d| _
|| _|| _|| _|| _|| _|| _|| _|| _dS )a  
        Construct an instance.

        Arguments:

          file_encoding: the name of the encoding to use by default when
            reading template files.  All templates are converted to unicode
            prior to parsing.  Defaults to the package default.

          string_encoding: the name of the encoding to use when converting
            to unicode any byte strings (type str in Python 2) encountered
            during the rendering process.  This name will be passed as the
            encoding argument to the built-in function unicode().
            Defaults to the package default.

          decode_errors: the string to pass as the errors argument to the
            built-in function unicode() when converting byte strings to
            unicode.  Defaults to the package default.

          search_dirs: the list of directories in which to search when
            loading a template by name or file name.  If given a string,
            the method interprets the string as a single directory.
            Defaults to the package default.

          file_extension: the template file extension.  Pass False for no
            extension (i.e. to use extensionless template files).
            Defaults to the package default.

          partials: an object (e.g. a dictionary) for custom partial loading
            during the rendering process.
                The object should have a get() method that accepts a string
            and returns the corresponding template as a string, preferably
            as a unicode string.  If there is no template with that name,
            the get() method should either return None (as dict.get() does)
            or raise an exception.
                If this argument is None, the rendering process will use
            the normal procedure of locating and reading templates from
            the file system -- using relevant instance attributes like
            search_dirs, file_encoding, etc.

          escape: the function used to escape variable tag values when
            rendering a template.  The function should accept a unicode
            string (or subclass of unicode) and return an escaped string
            that is again unicode (or a subclass of unicode).
                This function need not handle strings of type `str` because
            this class will only pass it unicode strings.  The constructor
            assigns this function to the constructed instance's escape()
            method.
                To disable escaping entirely, one can pass `lambda u: u`
            as the escape function, for example.  One may also wish to
            consider using markupsafe's escape function: markupsafe.escape().
            This argument defaults to the package default.

          missing_tags: a string specifying how to handle missing tags.
            If 'strict', an error is raised on a missing tag.  If 'ignore',
            the value of the tag is the empty string.  Defaults to the
            package default.

        N)r   ZDECODE_ERRORSZ
TAG_ESCAPEZFILE_ENCODINGZTEMPLATE_EXTENSIONZMISSING_TAGSZSEARCH_DIRSZSTRING_ENCODING
isinstancestr_contextdecode_errorsescapefile_encodingfile_extensionmissing_tagspartialssearch_dirsstring_encoding)	selfr   r   r   r   r   r   r   r    r   3/usr/lib/python3/dist-packages/pystache/renderer.py__init__1   s2   F

zRenderer.__init__c                 C   s   | j S )zG
        Return the current rendering context [experimental].

        )r   r   r   r   r   context   s   zRenderer.contextc                 C   s   t |S )aK  
        Coerce a non-string value to a string.

        This method is called whenever a non-string is encountered during the
        rendering process when a string is needed (e.g. if a context value
        for string interpolation is not a string).  To customize string
        coercion, you can override this method.

        )r   r   valr   r   r   
str_coerce   s   
zRenderer.str_coercec                 C   s   t |tr|S | |S )zT
        Convert a basestring to unicode, preserving any unicode subclass.

        )r   r   r   sr   r   r   _to_unicode_soft   s   

zRenderer._to_unicode_softc                 C   s   t | |S )zU
        Convert a basestring to a string with type unicode (not subclass).

        )r   r%   r#   r   r   r   _to_unicode_hard   s   zRenderer._to_unicode_hardc                 C   s   t | | |S )z
        Convert a basestring to unicode (preserving any unicode subclass), and escape it.

        Returns a unicode string (not subclass).

        )r   r   r%   r#   r   r   r   _escape_to_unicode   s   zRenderer._escape_to_unicodec                 C   s   |du r| j }t||| jS )a  
        Convert a byte string to unicode, using string_encoding and decode_errors.

        Arguments:

          b: a byte string.

          encoding: the name of an encoding.  Defaults to the string_encoding
            attribute for this instance.

        Raises:

          TypeError: Because this method calls Python's built-in unicode()
            function, this method raises the following exception if the
            given string is already unicode:

              TypeError: decoding Unicode is not supported

        N)r   r   r   )r   bencodingr   r   r   r      s   zRenderer.strc                 C   s   t | j| j| j| jdS )zE
        Create a Loader instance using current attributes.

        )r   	extensionZ
to_unicoder   )r   r   r   r   r   r   r   r   r   _make_loader   s   zRenderer._make_loaderc                    s   |     fdd}|S )zC
        Return a function that loads a template by name.

        c                    s
     | S N)	load_name)template_nameloaderr   r   load_template   s   
z3Renderer._make_load_template.<locals>.load_template)r+   )r   r1   r   r/   r   _make_load_template   s   zRenderer._make_load_templatec                    s*   j du r	 S j   fdd}|S )zB
        Return a function that loads a partial by name.

        Nc                    s4     | }|d u rtdt| t f |S )Nz!Name %s not found in partials: %s)getr   reprtyper&   )nametemplater   r   r   r   load_partial  s   

z1Renderer._make_load_partial.<locals>.load_partial)r   r2   )r   r9   r   r8   r   _make_load_partial  s
   
zRenderer._make_load_partialc                 C   s2   | j }|tjkr
dS |tjkrdS tdt| )z@
        Return whether missing_tags is set to strict.

        TFz$Unsupported 'missing_tags' value: %s)r   r   strictignore	Exceptionr4   r    r   r   r   _is_missing_tags_strict  s   

z Renderer._is_missing_tags_strictc                    s$   |    |  r
 S  fdd}|S )zZ
        Return the resolve_partial function to pass to RenderEngine.__init__().

        c                    s    z | W S  t y   Y dS w N )r   )r6   r9   r   r   resolve_partial6  s
   
z7Renderer._make_resolve_partial.<locals>.resolve_partial)r:   r>   )r   rB   r   rA   r   _make_resolve_partial+  s
   zRenderer._make_resolve_partialc                 C   s   |   rtS dd }|S )zZ
        Return the resolve_context function to pass to RenderEngine.__init__().

        c                 S   s"   zt | |W S  ty   Y dS w r?   )r
   r   )stackr6   r   r   r   resolve_contextG  s
   z7Renderer._make_resolve_context.<locals>.resolve_context)r>   r
   )r   rE   r   r   r   _make_resolve_context>  s   zRenderer._make_resolve_contextc                 C   s,   |   }|  }t| j| j||| jd}|S )z@
        Return a RenderEngine instance for rendering.

        )literalr   rE   rB   Zto_str)rF   rC   r   r&   r'   r"   )r   rE   rB   enginer   r   r   _make_render_engineO  s   zRenderer._make_render_enginec                 C   s   |   }||S )z@
        Load a template by name from the file system.

        )r2   )r   r.   r1   r   r   r   r1   a  s   zRenderer.load_templatec                 O   sV   |   }t|trt|}||}n||}|gt| }| j|g|R i |S )zH
        Render the template associated with the given object.

        )r+   r   r   r   loadZload_objectlist_render_string)r   objr   kwargsr0   r7   r   r   r   _render_objecti  s   

zRenderer._render_objectc                 O   *   |   }||}| j|g|R i |S )z
        Render the template with the given name using the given context.

        See the render() docstring for more information.

        )r+   r-   rL   )r   r.   r   rN   r0   r7   r   r   r   render_name  s   
zRenderer.render_namec                 O   rP   )z
        Render the template at the given path using the given context.

        Read the render() docstring for more information.

        )r+   readrL   )r   Ztemplate_pathr   rN   r0   r7   r   r   r   render_path  s   
zRenderer.render_pathc                    s.   |     fdd}| j|g|R i |S )zL
        Render the given template string using the given context.

        c                    s   |   |S r,   renderrH   rD   r7   r   r   <lambda>      z)Renderer._render_string.<locals>.<lambda>)r&   _render_finalr   r7   r   rN   render_funcr   rW   r   rL     s   
zRenderer._render_stringc                 O   s(   t j|i |}|| _|  }|||S )z
        Arguments:

          render_func: a function that accepts a RenderEngine and ContextStack
            instance and returns a template rendering as a unicode string.

        )r   Zcreater   rI   )r   r\   r   rN   rD   rH   r   r   r   rZ     s   
zRenderer._render_finalc                    sf   t  r| j g|R i |S t tr' fdd}| j|g|R i |S | j g|R i |S )a  
        Render the given template string, view template, or parsed template.

        Returns a unicode string.

        Prior to rendering, this method will convert a template that is a
        byte string (type str in Python 2) to unicode using the string_encoding
        and decode_errors attributes.  See the constructor docstring for
        more information.

        Arguments:

          template: a template string that is unicode or a byte string,
            a ParsedTemplate instance, or another object instance.  In the
            final case, the function first looks for the template associated
            to the object by calling this class's get_associated_template()
            method.  The rendering process also uses the passed object as
            the first element of the context stack when rendering.

          *context: zero or more dictionaries, ContextStack instances, or objects
            with which to populate the initial context stack.  None
            arguments are skipped.  Items in the *context list are added to
            the context stack in order so that later items in the argument
            list take precedence over earlier items.

          **kwargs: additional key-value data to add to the context stack.
            As these arguments appear after all items in the *context list,
            in the case of key conflicts these values take precedence over
            all items in the *context list.

        c                    s     | |S r,   rT   rV   rW   r   r   rX     rY   z!Renderer.render.<locals>.<lambda>)r   rL   r   r	   rZ   rO   r[   r   rW   r   rU     s    
zRenderer.render)NNNNNNNNr,   )__name__
__module____qualname____doc__r   propertyr   r"   r%   r&   r'   r   r+   r2   r:   r>   rC   rF   rI   r1   rO   rQ   rS   rL   rZ   rU   r   r   r   r   r      s@    
m
	
	r   N)r`   Zpystacher   Zpystache.commonr   r   r   Zpystache.contextr   r   Zpystache.loaderr   Zpystache.parsedr	   Zpystache.renderenginer
   r   Zpystache.specloaderr   Zpystache.template_specr   objectr   r   r   r   r   <module>   s   