parse the template referenced by this root node.
        note, this template structure is not guaranteed to be located within the root node's boundaries.

        Returns:
          TemplateNode: the template.
515026
def template(self):
        '''
        
        '''
        instance = self.template_instance()
        offset = self._chunk.offset() + instance.template_offset()
        node = TemplateNode(self._buf, offset, self._chunk, instance)
        return node
564986
def render(self, template, context_stack, delimiters=None):
        
        parsed_template = parse(template, delimiters)

        return parsed_template.render(self, context_stack)
1146542
def _scan_nodes(nodelist, context, instance_types, current_block=None, ignore_blocks=None):
    
    results = []
    for node in nodelist:
        # first check if this is the object instance to look for.
        if isinstance(node, instance_types):
            results.append(node)
            # if it's a Constant Include Node ({% include "template_name.html" %})
        # scan the child template
        elif isinstance(node, IncludeNode):
            # if there's an error in the to-be-included template, node.template becomes None
            if node.template:
                # This is required for Django 1.7 but works on older version too
                # Check if it quacks like a template object, if not
                # presume is a template path and get the object out of it
                if not callable(getattr(node.template, 'render', None)):
                    template = get_template(node.template.var)
                else:
                    template = node.template

                if TemplateAdapter is not None and isinstance(template, TemplateAdapter):
                    # Django 1.8: received a new object, take original template
                    template = template.template

                results += _scan_nodes(template.nodelist, context, instance_types, current_block)
        # handle {% extends ... %} tags
        elif isinstance(node, ExtendsNode):
            results += _extend_nodelist(node, context, instance_types)
        # in block nodes we have to scan for super blocks
        elif isinstance(node, VariableNode) and current_block:
            if node.filter_expression.token == 'block.super':
                # Found a {{ block.super }} line
                if not hasattr(current_block.parent, 'nodelist'):
                    raise TemplateSyntaxError(
                        "Cannot read {{{{ block.super }}}} for {{% block {0} %}}, "
                        "the parent template doesn't have this block.".format(
                        current_block.name
                    ))
                results += _scan_nodes(current_block.parent.nodelist, context, instance_types, current_block.parent)
        # ignore nested blocks which are already handled
        elif isinstance(node, BlockNode) and ignore_blocks and node.name in ignore_blocks:
            continue
        # if the node has the newly introduced 'child_nodelists' attribute, scan
        # those attributes for nodelists and recurse them
        elif hasattr(node, 'child_nodelists'):
            for nodelist_name in node.child_nodelists:
                if hasattr(node, nodelist_name):
                    subnodelist = getattr(node, nodelist_name)
                    if isinstance(subnodelist, NodeList):
                        if isinstance(node, BlockNode):
                            current_block = node
                        results += _scan_nodes(subnodelist, context, instance_types, current_block)
        # else just scan the node for nodelist instance attributes
        else:
            for attr in dir(node):
                obj = getattr(node, attr)
                if isinstance(obj, NodeList):
                    if isinstance(node, BlockNode):
                        current_block = node
                    results += _scan_nodes(obj, context, instance_types, current_block)
    return results
1106599
def parse_component_reference(self, node):
        

        if 'name' in node.lattrib:
            name = node.lattrib['name']
        else:
            self.raise_error('<ComponentReference> must specify a name for the ' +
                             'reference.')

        if 'type' in node.lattrib:
            type_ = node.lattrib['type']
        else:
            self.raise_error('<ComponentReference> must specify a type for the ' +
                             'reference.')
                             
        if 'local' in node.lattrib:
            local = node.lattrib['local']
        else:
            local = None

        self.current_component_type.add_component_reference(ComponentReference(name, type_, local))
1078383
def parse_template(self, tmp, reset=False, only_body=False):
        
        logging.debug('GoT: """\n%s\n"""', tmp)

        if self.sent_time:
            self.modified_since_sent = True

        if only_body:
            self.body = tmp
        else:
            m = re.match(r'(?P<h>([a-zA-Z0-9_-]+:.+\n)*)\n?(?P<b>(\s*.*)*)',
                         tmp)
            assert m

            d = m.groupdict()
            headertext = d['h']
            self.body = d['b']

            # remove existing content
            if reset:
                self.headers = {}

            # go through multiline, utf-8 encoded headers
            # we decode the edited text ourselves here as
            # email.message_from_file can't deal with raw utf8 header values
            key = value = None
            for line in headertext.splitlines():
                if re.match('[a-zA-Z0-9_-]+:', line):  # new k/v pair
                    if key and value:  # save old one from stack
                        self.add(key, value)  # save
                    key, value = line.strip().split(':', 1)  # parse new pair
                    # strip spaces, otherwise we end up having " foo" as value
                    # of "Subject: foo"
                    value = value.strip()
                elif key and value:  # append new line without key prefix
                    value += line
            if key and value:  # save last one if present
                self.add(key, value)

            # interpret 'Attach' pseudo header
            if 'Attach' in self:
                to_attach = []
                for line in self.get_all('Attach'):
                    gpath = os.path.expanduser(line.strip())
                    to_attach += [g for g in glob.glob(gpath)
                                  if os.path.isfile(g)]
                logging.debug('Attaching: %s', to_attach)
                for path in to_attach:
                    self.attach(path)
                del self['Attach']
1313563
def _make_load_template(self):
        
        loader = self._make_loader()

        def load_template(template_name):
            return loader.load_name(template_name)

        return load_template
171271
def build_tree(self):
        
        if self.built:
            return
        self.doc_root = self.root.element()
        for key in self.sorted_fields():
            if key not in self._fields:
                continue
            field = self._fields[key]
            if field != self.root:
                if isinstance(field, XmlModel):
                    field.build_tree()
                    if (self.drop_empty and field.drop_empty
                        and len(field.doc_root) == 0):
                        continue
                    self.doc_root.append(field.doc_root)
                elif isinstance(field, list):
                    # we just allow XmlFields and XmlModels
                    # Also xml as str for memory management
                    for item in field:
                        if isinstance(item, XmlField):
                            ele = item.element()
                            if self.drop_empty and len(ele) == 0:
                                continue
                            self.doc_root.append(ele)
                        elif isinstance(item, XmlModel):
                            item.build_tree()
                            if self.drop_empty and len(item.doc_root) == 0:
                                continue
                            self.doc_root.append(item.doc_root)
                        elif isinstance(item, (six.text_type, six.string_types)):
                            ele = etree.fromstring(clean_xml(item))
                            self.doc_root.append(ele)
                        item = None
                elif (field.parent or self.root.name) == self.root.name:
                    ele = field.element()
                    if self.drop_empty and len(ele) == 0 and not ele.text:
                        continue
                    ele = field.element(parent=self.doc_root)
                else:
                    nodes = [n for n in self.doc_root.iterdescendants(
                                            tag=field.parent)]
                    if nodes:
                        ele = field.element()
                        if (self.drop_empty and len(ele) == 0 and not ele.text):
                            continue
                        ele = field.element(parent=nodes[0])
                    #else:
                    #    raise RuntimeError("No parent found!")
        self.built = True
1186926
def _parse_tree(self, node):
        
        self.kind = node.tag
        if 'compare' in node.attrib:
            self.compare = node.attrib['compare']
        if 'version' in node.attrib:
            self.version = node.attrib['version']
        self.value = node.text
604472
def parse(self):
        
        if self.parse_string is not None and self._parse is None:
            self._parse = Tree.parse(self._parse_string)
        return self._parse
1257674
def parse(self):
        
        #print("Parsing: %s"%self.parse_string)
        self.tokenize()
        if self.debug: print("Tokens found: %s"%self.token_list)
        
        try:
            parse_tree = self.parse2()
        except Exception as e:
                raise e
        return parse_tree
1006142
def parse_template(template):
    """"""
    m = TEMPLATE_OVERRIDE_RE.match(template)
    if not m:
        return template, 0
    return m.group('template'), int(m.group('depth'))
925343
def _read_template(template):
    
    template = _read_content_or_path(template)
    file_obj = StringIO.StringIO(template)

    return ET.parse(file_obj)
595078
def load(self, name, parent_path=None):
        
        if name not in self.templates:
            self.templates[name] = self._create_template(name)
        return self.templates[name]
530412
def parse(self, content):
        
        raw = {}

        try:
            root = etree.fromstring(content)
        except SyntaxError as e:
            raise ValueError(*e.args)

        for child in root:
            raw[child.tag] = child.text

        formatted = self.format(raw)

        msg_type = formatted['type']
        msg_parser = getattr(self, 'parse_%s' % msg_type, None)
        if callable(msg_parser):
            parsed = msg_parser(raw)
        else:
            parsed = self.parse_invalid_type(raw)

        formatted.update(parsed)
        return formatted
116902
def node(self, parent=None, tag='g', attrib=None, **extras):
        """"""
        if parent is None:
            parent = self.root
        attrib = attrib or {}
        attrib.update(extras)

        def in_attrib_and_number(key):
            return key in attrib and isinstance(attrib[key], Number)

        for pos, dim in (('x', 'width'), ('y', 'height')):
            if in_attrib_and_number(dim) and attrib[dim] < 0:
                attrib[dim] = -attrib[dim]
                if in_attrib_and_number(pos):
                    attrib[pos] = attrib[pos] - attrib[dim]

        for key, value in dict(attrib).items():
            if value is None:
                del attrib[key]

            attrib[key] = to_str(value)
            if key.endswith('_'):
                attrib[key.rstrip('_')] = attrib[key]
                del attrib[key]
            elif key == 'href':
                attrib[etree.QName('http://www.w3.org/1999/xlink',
                                   key)] = attrib[key]
                del attrib[key]
        return etree.SubElement(parent, tag, attrib)
531986
def _make_section_node(self, template, tag_type, tag_key, parsed_section,
                           section_start_index, section_end_index):
        
        if tag_type == '#':
            return _SectionNode(tag_key, parsed_section, self._delimiters,
                               template, section_start_index, section_end_index)

        if tag_type == '^':
            return _InvertedNode(tag_key, parsed_section)

        raise Exception("Invalid symbol for section tag: %s" % repr(tag_type))
302820
def __getTemplate(template_file_name):
        
        with open(template_file_name) as template_file:
            template_raw = template_file.read()

        template = parse(template_raw)
        return template