當前位置: 首頁>>代碼示例>>Python>>正文


Python Renderer.render方法代碼示例

本文整理匯總了Python中pystache.renderer.Renderer.render方法的典型用法代碼示例。如果您正苦於以下問題:Python Renderer.render方法的具體用法?Python Renderer.render怎麽用?Python Renderer.render使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pystache.renderer.Renderer的用法示例。


在下文中一共展示了Renderer.render方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: render

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
def render(template, context=None, **kwargs):
    """
    Return the given template string rendered using the given context.

    """
    renderer = Renderer()
    return renderer.render(template, context, **kwargs)
開發者ID:SvetlanaM,項目名稱:EnabledCityPaloAlto,代碼行數:9,代碼來源:init.py

示例2: test

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
    def test(self):
        template = testData['template']
        partials = testData.has_key('partials') and testData['partials'] or {}
        expected = testData['expected']
        data     = testData['data']

        # Convert code strings to functions.
        # TODO: make this section of code easier to understand.
        new_data = {}
        for key, val in data.iteritems():
            if isinstance(val, dict) and val.get('__tag__') == 'code':
                val = eval(val['python'])
            new_data[key] = val

        renderer = Renderer(partials=partials)
        actual = renderer.render(template, new_data)
        actual = actual.encode('utf-8')

        message = """%s

  Template: \"""%s\"""

  Expected: %s
  Actual:   %s

  Expected: \"""%s\"""
  Actual:   \"""%s\"""
  """ % (description, template, repr(expected), repr(actual), expected, actual)

        self.assertEquals(actual, expected, message)
開發者ID:chuanzhang,項目名稱:pystache,代碼行數:32,代碼來源:test_spec.py

示例3: render

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
def render(template, context=None, name=None, **kwargs):
    """
    Return the given template string rendered using the given context.

    """
    renderer = Renderer()
    parsed_template = parse(template, name=name)
    return renderer.render(parsed_template, context, **kwargs)
開發者ID:GaloisInc,項目名稱:echronos,代碼行數:10,代碼來源:init.py

示例4: crear_plantilla

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
def crear_plantilla(archivo_fuente='user.c'):
    print "creando plantilla para archivo %s" % archivo_fuente
    renderer = Renderer()
    template = renderer.load_template(SOURCE_TEMPLATE)
    dato_plantilla = renderer.render(template, {'include_path': archivo_fuente})
    archivo = open(SOURCE_FILE, 'w')
    archivo.write(dato_plantilla)
    archivo.close()
    print "plantilla creada"
開發者ID:fitoria,項目名稱:icaro-cli,代碼行數:11,代碼來源:__init__.py

示例5: main

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
def main(sys_argv=sys.argv):
    template, context, c_format, multiple = parse_args(sys_argv, USAGE)

    if template.endswith('.mustache'):
        template = template[:-9]

    renderer = Renderer()

    try:
        template = renderer.load_template(template)
    except TemplateNotFoundError:
        pass

    if context.endswith(".csv") or (c_format and (c_format == "csv")):
        try:
            context = csv.DictReader(open(context, 'rb'))#, delimiter=',', quotechar='"')
        except IOError:
            print('ERROR: Could not parse context as CSV file. Check usage for input format options')
            exit(-1)            
    else:
        try:
            context = json.load(open(context))
        except IOError:
            context = json.loads(context)
        except ValueError: #likely a not well-formed JSON string, or user forgot -f csv.
            print('ERROR: Could not parse context as JSON file or text, check usage for input format options')
            exit(1)

    if (multiple):
        print ("multiple render on field %s" % multiple)
        fileName, fileExt = os.path.splitext(multiple)
        for i,c in enumerate(context):
            if multiple in c:
                f_name = str(c[multiple])
            else:                
                f_name = "%s-%03d%s" % (fileName, i, fileExt)
            with open(f_name, "w") as f: # mode "wx" could be used to prevent overwriting, + pass IOError, adding "--force" option to override.
                rendered = renderer.render(template, c)
                f.write(rendered)
                print ("%s done") % f_name
    else:
        rendered = renderer.render(template, context)
        print rendered
開發者ID:berteh,項目名稱:pystache,代碼行數:45,代碼來源:render.py

示例6: get

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
 def get(self):
     pass_phrase = self.authenticate_request()
     if pass_phrase:
         if self.check_setup():
             loader = Loader(extension='html', search_dirs=['view', 'view/setup'])
             renderer = Renderer(file_extension='html',
                 search_dirs=['view/partials', 'view/setup'])
             template = loader.load_name('setup')
             html = renderer.render(template, {"pass": pass_phrase})
             self.write(html)
         else:
             self.write("setup already completed.")
開發者ID:Web5design,項目名稱:autopilot,代碼行數:14,代碼來源:setup.py

示例7: get

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
    def get(self, article_name):

        article_name = article_name.lower()

        if article_name in BaseController.articles:

            article = BaseController.articles[article_name]

            # if content has not modified since last request
            # send a 304 not modified status
            modified_header_key = "If-Modified-Since"
            if modified_header_key in self.request.headers:
                if (self.request.headers["If-Modified-Since"] ==
                    article['modified_date']):
                    self.set_status(304)
                    return

            if (BaseController.settings['enable_caching'] and
                article_name in BaseController.cached_articles):
                html = BaseController.cached_articles[article_name]
            else:
                view_model = {
                "article": article,
                "site_name": BaseController.settings['site_name']
                }
                self.attach_meta_data(view_model)

                loader = Loader(file_encoding='utf8',
                                extension='html',
                                search_dirs=['view', ])
                renderer = Renderer(file_encoding='utf8',
                                    file_extension='html',
                                    search_dirs=['view/partials'])
                template = loader.load_name('article')
                html = renderer.render(template, view_model)

                # cache the html
                BaseController.cached_articles[article_name] = html

            # set http caching headers
            if "http_caching_max_age" in BaseController.settings:
                max_age = BaseController.settings["http_caching_max_age"]
            else:
                max_age = 60
            self.set_header("Cache-control", "max-age=%s" % max_age)
            self.set_header("Last-Modified", article['modified_date'])
            self.write(html)

        else:
            raise tornado.web.HTTPError(404)
開發者ID:Web5design,項目名稱:autopilot,代碼行數:52,代碼來源:article.py

示例8: generate_page

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
    def generate_page(self, articles):
        view_model = {
                    "articles": articles,
                    "site_name": BaseController.settings["site_name"]
                    }
        self.attach_meta_data(view_model)

        loader = Loader(file_encoding='utf8', extension='html',
                        search_dirs=['view', ])
        renderer = Renderer(file_encoding='utf8', file_extension='html',
                            search_dirs=['view/partials'])
        template = loader.load_name('list')
        html = renderer.render(template, view_model)
        return html
開發者ID:Web5design,項目名稱:autopilot,代碼行數:16,代碼來源:list.py

示例9: render

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
    def render(self, content, data):
        """
        Render the given ``content`` as template with the ``data`` dictionary.

        Args:
            content (str): The template content to render.
            data (dict): The data dictionary to render.

        Returns:
            str: The rendered template text

        """

        stache = Renderer(partials=self._partials_loader)
        return stache.render(content, data)
開發者ID:datafolklabs,項目名稱:cement,代碼行數:17,代碼來源:ext_mustache.py

示例10: render

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
    def render(self, data_dict, template):
        """
        Take a data dictionary and render it using the given template file.

        Required Arguments:

        :param data_dict: The data dictionary to render.
        :param template: The path to the template, after the
         ``template_module`` or ``template_dirs`` prefix as defined in the
         application.
        :returns: str (the rendered template text)

        """

        LOG.debug("rendering output using '%s' as a template." % template)
        content = self.load_template(template)
        stache = Renderer(partials=self._partials_loader)
        return stache.render(content, data_dict)
開發者ID:Ichag,項目名稱:cement,代碼行數:20,代碼來源:ext_mustache.py

示例11: main

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
def main(sys_argv=sys.argv):
    template, context = parse_args(sys_argv, USAGE)

    if template.endswith('.mustache'):
        template = template[:-9]

    renderer = Renderer()

    try:
        template = renderer.load_template(template)
    except IOError:
        pass

    try:
        context = json.load(open(context))
    except IOError:
        context = json.loads(context)

    rendered = renderer.render(template, context)
    print rendered
開發者ID:tobiasandtobias,項目名稱:pystache,代碼行數:22,代碼來源:render.py

示例12: main

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
def main(argv=None):
    if argv is None:
        argv = sys.argv

    template, context, options = parse_args(argv, USAGE)

    if context is None and not sys.stdin.isatty():
        user_context, _ = read_yaml_frontmatter(sys.stdin)
    elif context:
        content = arg2text(context)
        user_context, _ = extract_context(content, greedy=True)
    else:
        user_context = {}

    # assuming first arg is a filename or template literal
    template = arg2text(template)
    template_context, template = extract_context(template)
    template_context.update(user_context)
    renderer = Renderer()
    rendered = renderer.render(template, template_context)
    print(rendered.encode('utf-8'))
開發者ID:charbeljc,項目名稱:pystache,代碼行數:23,代碼來源:render.py

示例13: _runTest

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
    def _runTest(self):
        context = self._context
        description = self._description
        expected = self._expected
        file_path = self._file_path
        partials = self._partials
        template = self._template
        test_name = self._test_name

        renderer = Renderer(partials=partials)
        actual = renderer.render(template, context)

        # We need to escape the strings that occur in our format string because
        # they can contain % symbols, for example (in delimiters.yml)--
        #
        #   "template: '{{=<% %>=}}(<%text%>)'"
        #
        def escape(s):
            return s.replace("%", "%%")

        parser_info = _get_parser_info()
        subs = [repr(test_name), description, os.path.abspath(file_path),
                template, repr(context), parser_info]
        subs = tuple([escape(sub) for sub in subs])
        # We include the parsing module version info to help with troubleshooting
        # yaml/json/simplejson issues.
        message = """%s: %s

  File: %s

  Template: \"""%s\"""

  Context: %s

  %%s

  [using %s]
  """ % subs

        self.assertString(actual, expected, format=message)
開發者ID:Abixer,項目名稱:croomcroom,代碼行數:42,代碼來源:spectesting.py

示例14: get

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
    def get(self):

        if (BaseController.settings['enable_caching'] and
            BaseController.cached_home):
            html = BaseController.cached_home
            self.write(html)
        else:
            published_articles = []
            for article in BaseController.articles.values():
                if article['date'] is not None:
                    published_articles.append(article)

            articles = sorted(published_articles,
                              key=operator.itemgetter("date"),
                              reverse=True)

            max_articles_count = BaseController.settings["homepage_max_articles"]
            show_archive = False
            if len(articles) > max_articles_count:
                show_archive = True
                articles = articles[0:max_articles_count]

            view_model = {
                        "articles": articles,
                        "showArchive": show_archive,
                        "site_name": BaseController.settings["site_name"]
                        }
            self.attach_meta_data(view_model)
            loader = Loader(file_encoding='utf8', extension='html',
                        search_dirs=['view', ])
            renderer = Renderer(file_encoding='utf8', file_extension='html',
                            search_dirs=['view/partials'])
            template = loader.load_name('home')
            html = renderer.render(template, view_model)

            # cache the home page
            BaseController.cached_home = html

            self.write(html)
開發者ID:Web5design,項目名稱:autopilot,代碼行數:41,代碼來源:home.py

示例15: test

# 需要導入模塊: from pystache.renderer import Renderer [as 別名]
# 或者: from pystache.renderer.Renderer import render [as 別名]
    def test(self):
        template = testData['template']
        partials = testData.has_key('partials') and testData['partials'] or {}
        expected = testData['expected']
        data     = testData['data']

        renderer = Renderer(partials=partials)
        actual = renderer.render(template, data)
        actual = actual.encode('utf-8')

        message = """%s

  Template: \"""%s\"""

  Expected: %s
  Actual:   %s

  Expected: \"""%s\"""
  Actual:   \"""%s\"""
  """ % (description, template, repr(expected), repr(actual), expected, actual)

        self.assertEquals(actual, expected, message)
開發者ID:jakearchibald,項目名稱:pystache,代碼行數:24,代碼來源:test_spec.py


注:本文中的pystache.renderer.Renderer.render方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。