• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pystache.render函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pystache.render函数的典型用法代码示例。如果您正苦于以下问题:Python render函数的具体用法?Python render怎么用?Python render使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了render函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: render

    def render(self, data={}):
        """
        Runs the raw markdown through mustache, then converts it to HTML with
        markdown, and finally renders the template with the converted markdown
        to produce the final page.

        :param data: An optional dict of additional data that gets passed to
        the mustache templates while they render.
        """
        extra_tmpls = {}
        data.update({"time": time,
                     "date": date,
                     "site_title": config["site_title"]})
        data.update(self.page_config)

        for tmpl in raw_extra_tmpls:
            extra_tmpls[tmpl] = pystache.render(raw_extra_tmpls[tmpl], data)

        data.update({"files": extra_tmpls})

        templated_markdown = pystache.render(self.raw_markdown, data)
        data["content"] = markdown(templated_markdown, extensions=['extra'])

        template = self.page_config["template"] if "template" in self.page_config else "single"
        template_path = whats_where["templates"] + "/" + template + extension

        with open(template_path, "r") as tmpl_data:
            raw_tmpl = unicode(tmpl_data.read())

        self.rendered_final = pystache.render(raw_tmpl, data)
开发者ID:JoshAshby,项目名称:board,代码行数:30,代码来源:board.py


示例2: renderPost

def renderPost(post, posts):
  metadata = {}
  for k, v in post[0].iteritems():
    metadata[k] = v[0]
  metadata[u'content'] = post[1]
  metadata[u'sitename'] = sitename
  metadata[u'webRoot'] = webRoot
  metadata[u'author'] = author
  metadata[u'typekitId'] = typekitId
  postName = removePunctuation(metadata[u'title'])
  postName = metadata[u'date'].split(' ')[0] + '-' + postName.replace(u' ',u'-').replace(u'‑',u'-')
  postName = u'-'.join(postName.split('-'))
  postFileName = outputDir + postName + '.html'
  metadata[u'postURL'] = webRoot + postName + '.html'
  metadata[u'title'] = unicode(mdx_smartypants.unicode_entities(metadata[u'title']))
  if u'link' in metadata:
    templateType = u'/post-content-link.html'
  else:
    templateType = u'/post-content.html'
  with open(templateDir + templateType,'r','utf-8') as f:
    postContentTemplate = f.read()
    postContent = pystache.render(postContentTemplate,metadata,decode_errors='ignore')
    metadata['post-content'] = postContent
  with open(templateDir + u'/post-page.html','r','utf-8') as f:
    postPageTemplate = f.read()
    postPageResult = pystache.render(postPageTemplate,metadata,decode_errors='ignore')
  with open(postFileName,'w','utf-8') as f:
    f.write(postPageResult)
  return posts.append(metadata)
开发者ID:JoeIsHere,项目名称:yakbarber,代码行数:29,代码来源:yakbarber.py


示例3: nanny

def nanny():
    """Nanny reciever endpoint

    if recieved is post and legit json, app.config['NANNY_TEMPLATE'] is then
    passed to pystache, otherwise app.config['NANNY_SCRIPT'] is used directly.

    ALWAYS returns true, no questions asked
    """
    data = request.get_json()

    for t, p in app.config.get('NANNY_PEEK', []):
        to_peek = pystache.render(t, data)
        m = re.match(p, to_peek)
        if not m:
            logging.info('unable to match re %s with %s (from template %s)', p, to_peek, t)
            abort(400)
        data.update(m.groupdict())

    template = app.config['NANNY_TEMPLATE']

    script = pystache.render(template, request.json)

    if not script.strip():
        logging.info('Nanny got empty script, ignoring...')
        abort(400)

    logging.info('Nanny to run script: \n%s', script)
    subprocess.Popen(script, shell=True)
    return jsonify(status='OK')
开发者ID:tdihp,项目名称:callbacknanny,代码行数:29,代码来源:callbacknanny.py


示例4: play_or_say

def play_or_say(r, audio, **kwds):
    """
    Take twilio response and play or say message from an AudioRecording
    Can use mustache templates to render keyword arguments
    """

    if audio:
        if (hasattr(audio, 'text_to_speech') and not (audio.text_to_speech == '')):
            msg = pystache.render(audio.text_to_speech, kwds)
            r.say(msg)
        elif (hasattr(audio, 'file_storage') and (audio.file_storage.fp is not None)):
            r.play(audio.file_url())
        elif type(audio) == str:
            try:
                msg = pystache.render(audio, kwds)
                r.say(msg)
            except Exception:
                current_app.logger.error('Unable to render pystache template %s' % audio)
                r.say(audio)
        else:
            current_app.logger.error('Unknown audio type %s' % type(audio))
    else:
        r.say('Error: no recording defined')
        current_app.logger.error('Missing audio recording')
        current_app.logger.error(kwds)
开发者ID:EFForg,项目名称:call-congress,代码行数:25,代码来源:views.py


示例5: main

def main():
	dumpPath = r'..\examples\dump.cpp.json'
	projPath = r'C:\Users\paperweight\Source\Repos\Tod\Tod.vcxproj'
	namespaces = ['tod']
	moduleNames = ['cppcli_blanket']
	modules = map(__import__, moduleNames)

	pyclump.DumpAST(projPath, namespaces, dumpPath)

	f = open(dumpPath, 'r')
	data = f.read()
	meta = json.loads(data)
	f.close()

	a = modules[0].Transform(meta)
	a.Execute()

	# TODO: transform dump.json into dump.cppcli.json into dump.<class>.h/dump.<class>.cpp/dump.csproj/dump.sln
	for clas in meta:

		if clas['subtype'] == 'factory':
			clas['subtype'] = 'static class'
		elif clas['subtype'] == 'class':
			clas['subtype'] = 'ref class'

		clas['projectname'] = 'tod'

	f = open(r'..\templates\cppcli.pst', 'r')
	template = f.read()
	f.close()

	outputFolder = ".\examples"
	print meta
	for clas in meta:
		print pystache.render(template, clas)
开发者ID:paperweight86,项目名称:pyBlanket,代码行数:35,代码来源:pyblanket.py


示例6: print_summary

def print_summary(failed_builds, total_builds, html=False):
    # All the templates
    count = [
        "{{failed}} of {{total}} regressions failed",
        "<p><b>{{failed}}</b> of <b>{{total}}</b> regressions failed</p>",
    ]
    regression_link = [
        "\tRegression Link: {{link}}\n" "\tNode: {{node}}",
        "<p>&emsp;Regression Link: {{link}}</p>" "<p>&emsp;Node: {{node}}</p>",
    ]
    component = ["\tComponent: {{comp}}", "<p>&emsp;Component: {{comp}}</p>"]
    failure_count = [
        "".join([TERM.red, "{{test}} ; Failed {{count}} times", TERM.normal]),
        ('<p><font color="red"><b>{{test}};</b> Failed <b>{{count}}' "</b> times</font></p>"),
    ]

    template = 0
    if html:
        template = 1
    print render(count[template], {"failed": failed_builds, "total": total_builds})
    for k, v in summary.iteritems():
        if k == "core":
            print "".join([TERM.red, "Found cores:", TERM.normal])
            for comp, link in zip(v[::2], v[1::2]):
                print render(component[template], {"comp": comp})
                print render(regression_link[template], {"link": link[0], "node": link[1]})
        else:
            print render(failure_count[template], {"test": k, "count": len(v)})
            for link in v:
                print render(regression_link[template], {"link": link[0], "node": link[1]})
开发者ID:kshlm,项目名称:glusterfs,代码行数:30,代码来源:failed-tests.py


示例7: create_post_page

def create_post_page(config,post_file_name):
    project_path = config['path']
    posts_folder = os.path.join(project_path,'posts')
    
    post = [parse_post(config,os.path.join(posts_folder,post_file_name))]

    if config['debug']:
        url = config['path']
    else:
        url = config['url']

    if config['disqus']['enabled']:
        disqus_template = open(path.DISQUS_TEMPLATE).read()
        disqus_variables = config['disqus']
        disqus_variables.update({'disqus_url':url + '/pages/permalinks/' + post_file_name[:-3] + '.html',
                                 'disqus_identifier':post_file_name[:-3]})
        disqus = pystache.render(disqus_template,disqus_variables)
        disqus = unicode(disqus)
    else:
        disqus = ''
    page_content = {'posts':post,
                    'blog_name':config['blog_name'],
                    'blog_description':config['blog_description'],
                    'url':url,
                    'about_author':config['about_author'],
                    'contacts':config['contacts'],
                    'links':config['links'],
                    'css_file':config['css_file'],
                    'old_posts':get_permalinks_list(config),
                    'disqus':disqus,
                    'footage_content':config['footage_content'],
                    }

    template = open(path.INDEX_TEMPLATE).read()
    return pystache.render(template,page_content)
开发者ID:alvesjnr,项目名称:speechhub,代码行数:35,代码来源:functions.py


示例8: rendertemplate

def rendertemplate(type):
    body = ''
    if type == 'html':
        summary = pystache.render(html_summary_tmpl, {
            'total': stats['total'],
            'addr': stats['addresses'],
            'nodes': stats['nodes'],
            'ways': stats['ways'],
            'date': now.strftime("%B %d, %Y")
        })
    elif type == 'text':
        summary = pystache.render(text_summary_tmpl, {
            'total': stats['total'],
            'addr': stats['addresses'],
            'nodes': stats['nodes'],
            'ways': stats['ways'],
            'date': now.strftime("%B %d, %Y")
        })
    # Add summary
    body+=summary
    for c in cids:
        if type == 'html':
            header = pystache.render(html_headers_tmpl, {
                'changeset': c,
            })
        elif type == 'text':
            header = pystache.render(text_headers_tmpl, {
                'changeset': c,
            })
        # Add header for each changeset ID
        body+=header
        for each in finalobject[c]:
            # Add changes, grouped by tags
            body+=renderChanges(each, type)
    return body
开发者ID:mapbox,项目名称:changewithin,代码行数:35,代码来源:changewithin.py


示例9: send_confirmation

def send_confirmation(user, followMod=None):
    with open("emails/confirm-account") as f:
        if followMod != None:
            message = pystache.render(
                f.read(),
                {
                    "user": user,
                    "site-name": _cfg("site-name"),
                    "domain": _cfg("domain"),
                    "confirmation": user.confirmation + "?f=" + followMod,
                },
            )
        else:
            message = html.parser.HTMLParser().unescape(
                pystache.render(
                    f.read(),
                    {
                        "user": user,
                        "site-name": _cfg("site-name"),
                        "domain": _cfg("domain"),
                        "confirmation": user.confirmation,
                    },
                )
            )
    send_mail.delay(
        _cfg("support-mail"), [user.email], "Welcome to " + _cfg("site-name") + "!", message, important=True
    )
开发者ID:CliftonMarien,项目名称:SpaceDock,代码行数:27,代码来源:email.py


示例10: generate_xmls

def generate_xmls(json_filenames):
    xml_template_str = unicode(open('tool-template.xml').read())
    xml_template = pystache.parse(xml_template_str)
    for tool_path in json_filenames:
        desc = json.load(open(tool_path))
        desc['collectionName'] = desc['collectionName'].capitalize()
        print pystache.render(xml_template, desc)
开发者ID:edamontology,项目名称:toolinfowarehouse,代码行数:7,代码来源:json2xml.py


示例11: main

def main():
    url = 'http://docs.python.org/2/library/datetime.html'
    body = urllib2.urlopen(url).read()
    soup = BeautifulSoup(body)

    table = soup.find(id='strftime-and-strptime-behavior').find('table')
    example_date = datetime.datetime(2013, 12, 25, 17, 15, 30)

    directives = []
    for row in table.select('tbody > tr'):
        tds = row.find_all('td')
        directive = tds[0].find('span').string
        # we use getText() here because some of the meanings have extra markup
        meaning = tds[1].getText().replace('\n', ' ')
        example = example_date.strftime(directive)
        directives.append({
            'directive': directive,
            'meaning': meaning,
            'example': example,
        })

    template = open('templates/index.html.mustache').read()
    context = {
        'example_date': str(example_date),
        'example_date_repr': repr(example_date),
        'directives': directives,
        'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%d'),
    }
    print pystache.render(template, context).encode('utf8')
    return 0
开发者ID:blha303,项目名称:strftime.org,代码行数:30,代码来源:build.py


示例12: play_or_say

def play_or_say(r, audio, voice='alice', lang='en-US', **kwargs):
    """
    Take twilio response and play or say message from an AudioRecording
    Can use mustache templates to render keyword arguments
    """

    if audio:
        # check to ensure lang is in list of valid locales
        if lang not in TWILIO_TTS_LANGUAGES:
            if '-' in lang:
                lang, country = lang.split('-')
            else:
                lang = 'en'

        if (hasattr(audio, 'text_to_speech') and audio.text_to_speech):
            msg = pystache.render(audio.text_to_speech, kwargs)
            r.say(msg, voice=voice, language=lang)
        elif (hasattr(audio, 'file_storage') and (audio.file_storage.fp is not None)):
            r.play(audio.file_url())
        elif type(audio) == str:
            try:
                msg = pystache.render(audio, kwargs)
                r.say(msg, voice=voice, language=lang)
            except pystache.common.PystacheError:
                current_app.logger.error('Unable to render pystache template %s' % audio)
                r.say(audio, voice=voice, language=lang)
        else:
            current_app.logger.error('Unknown audio type %s' % type(audio))
    else:
        r.say('Error: no recording defined')
        current_app.logger.error('Missing audio recording')
        current_app.logger.error(kwargs)
开发者ID:18mr,项目名称:call-congress,代码行数:32,代码来源:views.py


示例13: results

def results(request):
    params = rewrite_params(request).copy()
    del params['_escaped_fragment_']
    
    if not len(params):
        return HttpResponseNotFound()

    if not params.has_key('page'): params['page'] = 1
    if not params.has_key('sorting'): params['sorting'] = '_score'

    query = {}
    
    for param in params:
        query[param] = urllib2.unquote(unicode(params[param]))

    search = SearchHandler().create(InjectRequest(query))
    loader = Loader()

    items = pystache.render(
        loader.load_template_source('pages/search/items.html')[0], 
        search['results']
    )
    
    facets = ''
    
    if search.has_key('facets') and search['facets'].has_key('company.facet'):
        facets = pystache.render(
            loader.load_template_source('pages/search/facets.html')[0], 
            {'facets' : search['facets']['company.facet']}
        ) 
        
    term = ''

    if (query.has_key('what') and len(query['what'])) and (query.has_key('where') and len(query['where'])): 
        term = '%s / %s' % (query['what'].lower(), query['where'].lower())
    elif query.has_key('what'): term = query['what'].lower()
    elif query.has_key('where'): term = query['where'].lower()
    
    total = 0
    
    if len(search['results']):
        total = search['results']['total'] 
        
    pagination = ''
    
    if len(search['results']) and len(search['results']['pagination']) > 1:
        pagination =  pystache.render(
            loader.load_template_source('pages/search/pagination.html')[0], 
            {'pagination' : search['results']['pagination'] }
        )
    
    content = render_to_string('pages/search.html', {
        'term': term, 'total': total, 'facets': facets, 
        'items': items, 'pagination': pagination
    }, context_instance=RequestContext(request))
    
    return direct_to_template(request, 'base.html', {
         'search': content, 'job_count': count_documents()
    })
开发者ID:7loops,项目名称:zaposlim.se,代码行数:59,代码来源:views.py


示例14: index

 def index(self):
     global page_template, entry_template, path
     entries = glob.glob(os.path.join(entries_path, '*.entry'))
     entries.sort(key = lambda x: os.path.getmtime(x), reverse = True)
     content = u""
     for entry in entries:
         content = content + pystache.render(entry_template, entry_from_file(entry, entry == entries[-1]))
     return pystache.render(page_template, {'content': content})
开发者ID:lampholder,项目名称:notblog,代码行数:8,代码来源:doba.py


示例15: generate_final

    def generate_final(self, context, dest=os.getcwd()):

        if self.config.verbose:
            scanner = Scanner(self.template, self.templates)
            keys = scanner.scan()
            for key in keys:
                if key in context:
                    if callable(context[key]):
                        print "%s: %s" % (key, context[key]())
                    else:
                        print "%s: %s" % (key, context[key])


        source = os.path.join(self.templates, self.template)

        import tempfile, time
        tmp_dest = os.path.join(tempfile.gettempdir(), str(int(time.time())))

        # copy to temp destination
        self.merge_folder(source, tmp_dest)

        os.remove(os.path.join(tmp_dest, "description.yml"))
        os.remove(os.path.join(tmp_dest, "dynamic.py"))

        # render content
        for root, dirs, files in os.walk(tmp_dest):
            if files:
                for name in files:
                    with open(os.path.join(root, name), 'r+') as f:
                        print "rendering %s ..." % os.path.join(root, name)
                        template = unicode(f.read(), "UTF-8")
                        f.seek(0)
                        f.truncate()
                        f.write(pystache.render(template, context).encode("UTF-8"))

        # folder names
        for root, dirs, files in os.walk(tmp_dest):
            if dirs:
                for dir_ in map(lambda i: os.path.join(root, i), dirs):
                    parsed = pystache.parser.parse(unicode(dir_, "UTF-8"))
                    if any(hasattr(item, 'key') for item in parsed._parse_tree):
                        new_dir = os.path.join(root, pystache.render(dir_, context))
                        if not os.path.exists(new_dir):
                            os.makedirs(new_dir)
                        for template in os.listdir(dir_):
                            shutil.copy(os.path.join(dir_, template), new_dir)
                        shutil.rmtree(dir_)

        # file names
        for root, dirs, files in os.walk(tmp_dest):
            if files:
                for f in map(lambda i: os.path.join(root, i), files):
                    parsed = pystache.parser.parse(unicode(f, "UTF-8"))
                    if any(hasattr(item, 'key') for item in parsed._parse_tree):
                        # rename
                        os.rename(f, pystache.render(parsed, context))

        self.merge_folder(tmp_dest, dest)
开发者ID:andyhorng,项目名称:nanny,代码行数:58,代码来源:scaffolding.py


示例16: renderIndex

 def renderIndex(self, path):
     pages = self.getPagesByPath(path)
     s = ""
     col = sorted([page for page in pages if not "noroll" in page.meta], key=lambda page: (page.meta.get("date","").isoformat(), page.meta.get("title")) ,reverse=True)
     counter = 0
     for page in col:
            counter += 1
            if counter < 4:
                if counter > 1:
                    s += "<hr>"
                s += '<section><h2><a href="'+page.getPageURL()+'">'+page.meta.get("title","")+'</a></h2>\n<h5>'+page.meta.get("date","").strftime("%d.%m.%Y")+'</h5>'
                s += page.intro
                if page.hasIntro:
                    s += '<a href="'+page.getPageURL()+'">more...</a>\n</section>'
                
            if counter == 4:
                s += "<hr><h3>Older articles:</h3>\n"
            if counter >= 4:
                s += '<h4><a href="'+page.getPageURL()+'">'+page.meta.get("title","")+'</a></h4>\n'
     title = PAGE_TITLE
     if path != "": title += " // ".join(path.split("/"))
     indexFile = "index.html"
     pathToIndexFile = fixString(path.replace(" ", "_")).lower().strip("/")
     if len(pathToIndexFile) > 0: indexFile = pathToIndexFile + "/" +indexFile
     linkToIndex = BASIC_URL.strip("/")+"/"+ indexFile
     rss = '<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0">\n<channel>\n<title>'+title+'</title>\n'
     rss += "<link>"+linkToIndex+"</link>\n<description></description>\n<language>de</language>\n"
     for page in [page for page in pages[0:10] if not "noroll" in page.meta]:
             rss += '<item>\n<title>'+page.meta.get("title","")+'</title>\n<description><![CDATA['+page.content+']]></description>\n<link>'+page.getPageURL()+'</link>\n<guid>'+page.getPageURL()+'</guid>\n<pubDate>'+page.meta.get("date","").strftime("%a, %d %b %Y") + " 00:00:00 +0000" +'</pubDate>\n</item>\n'
     rss += "</channel>\n</rss>\n"
     data = {}
     data["page_title"] = title
     data["page_author"] = AUTHOR
     data["navigation"] = self.renderNavigation()
     data["description"] = ""
     if path == "":
         data["page_description"] = DESCRIPTION
     data["content"] = s
     data["feed"] = os.path.splitext(indexFile)[0]+".rss"
     data["site_name"] = PAGE_TITLE
     data["footer_message"] = FOOTER_MESSAGE
     content = pystache.render(template, data)
     
     directory = os.path.dirname(indexFile)
     if directory != "":
         if not os.path.exists(directory):
             os.makedirs(directory)
     fp = open(indexFile, "w")
     fp.write(content)
     fp.close()
     fp = open(os.path.splitext(indexFile)[0]+".rss", "w")
     fp.write(rss)
     fp.close()
     sitemap_template = "<url>\n<loc>{{url}}</loc>\n<lastmod>{{date}}</lastmod>\n</url>\n"
     self.IndexURLSitemap += pystache.render(sitemap_template, {'url': BASIC_URL.strip("/")+"/"+indexFile, 'date': col[0].meta.get("date","").isoformat()})
     nextPaths = self.getNextPaths(path)
     for element in nextPaths:
         self.renderIndex(path+"/"+element)
开发者ID:LRiecken,项目名称:PagePool,代码行数:58,代码来源:pagepool.py


示例17: send_confirmation

def send_confirmation(user, followMod=None):
    with open("emails/confirm-account") as f:
        if followMod != None:
            message = pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"),\
                    'confirmation': user.confirmation + "?f=" + followMod })
        else:
            message = html.parser.HTMLParser().unescape(\
                    pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.confirmation }))
    send_mail.delay(_cfg('support-mail'), [ user.email ], "Welcome to " + _cfg('site-name') + "!", message, important=True)
开发者ID:Electro-ninja,项目名称:KerbalStuff,代码行数:9,代码来源:email.py


示例18: copy_file_from_src

def copy_file_from_src(build_params, filename, dest):
	filename = pystache.render(filename, build_params['app_config'])
	dest = pystache.render(dest, build_params['app_config'])
	if os.path.isfile(os.path.join(build_params['src_path'], filename)):
		if not os.path.exists(os.path.dirname(os.path.join(build_params['project_path'], dest))):
			os.makedirs(os.path.dirname(os.path.join(build_params['project_path'], dest)))
		shutil.copy2(os.path.join(build_params['src_path'], filename), os.path.join(build_params['project_path'], dest))
	elif filename != "":
		raise Exception("Could not find file: %s" % filename)
开发者ID:homerjam,项目名称:file2,代码行数:9,代码来源:build_steps_local.py


示例19: do_GET

    def do_GET(self):
        parsed_path = urlparse.urlparse(self.path)
        loc = parsed_path.path[1:] # the first char in a '/' so skip it
        size = parsed_path.params
        if os.path.exists(loc):
            # static file, guess the content-type and serve
            src = open(loc).read()
            self.send_response(200)
            mime, enc = mimetypes.guess_type(loc)
            if (mime):
                self.send_header("content-type", mime) 
            self.end_headers()
            self.wfile.write(src)
        else:
            # render a mustache template based on the url
            url_parts = loc.split('/')
            app = url_parts[0]
            context = self.common_context.copy()

            if len(url_parts) == 1:
                template_name = '%s_list' % app
                context_fn = os.path.join("fixtures", app, "list.json")

            else:
                template_name = 'agenda_detail'
                fixture_name = "%s.json" % url_parts[1]
                context_fn = os.path.join("fixtures", app, fixture_name)

            if os.path.exists(context_fn):
                context.update(json.load(open(context_fn)))

            if size == 's':
                dump = {"template": open(os.path.join("templates", app, "%s.mustache"% template_name)).read(), 
                        "context": json.dumps(context),
                        "app": open(os.path.join("templates", app, "%s.js"% template_name)).read(),
                        "partials" : json.dumps(get_partials()),
                       }
                template_name = 'small_base'

            template = self.loader.load_template(template_name, encoding='utf-8')
            if not template:
                self.send_response(500)
                self.end_headers()
                return

            context['_'] = lambda x: self.translation.ugettext(x)
            html = pystache.render(template, context)

            if size == 's':
                html = pystache.render(template, context) % dump

            # response headers
            self.send_response(200)
            self.send_header("content-type", "text/html") # 200 in an HTTP OK Result Code
            self.end_headers()
            # and the content
            self.wfile.write(html.encode('utf-8'))
开发者ID:Bren,项目名称:ok-templates,代码行数:57,代码来源:server.py


示例20: send

    def send(self, request, recipients=None, data=None):
        datadict = {}
        datadict["device"] = {
            "description": data["device"].description,
            "devicetype": (data["device"].devicetype.name if data["device"].devicetype != None else ""),
            "group": data["device"].group,
            "hostname": data["device"].hostname,
            "inventoried": data["device"].inventoried,
            "inventorynumber": data["device"].inventorynumber,
            "manufacturer": data["device"].manufacturer,
            "name": data["device"].__unicode__(),
            "room": (
                data["device"].room.name + " (" + data["device"].room.building.name + ")"
                if data["device"].room != None
                else ""
            ),
            "serialnumber": data["device"].serialnumber,
            "templending": data["device"].templending,
            "trashed": data["device"].trashed,
            "webinterface": data["device"].webinterface,
            "department": data["device"].department,
        }
        if data["device"].currentlending != None:
            datadict["device"]["currentlending"] = (
                {
                    "owner": data["device"].currentlending.owner.__unicode__(),
                    "duedate": data["device"].currentlending.duedate,
                    "lenddate": data["device"].currentlending.lenddate,
                },
            )
        else:
            datadict["device"]["currentlending"] = ""

        datadict["user"] = {
            "username": data["user"].username,
            "first_name": data["user"].first_name,
            "last_name": data["user"].last_name,
        }
        if "owner" in data:
            datadict["owner"] = {
                "username": data["owner"].username,
                "first_name": data["owner"].first_name,
                "last_name": data["owner"].last_name,
            }
        body = pystache.render(self.body, datadict)
        subject = pystache.render(self.subject, datadict)

        email = EmailMessage(subject=subject, body=body, to=recipients)
        email.send()
        mailhistory = MailHistory()
        mailhistory.mailtemplate = self
        mailhistory.subject = self.subject
        mailhistory.body = body
        mailhistory.sent_by = request.user
        if "device" in data:
            mailhistory.device = data["device"]
        mailhistory.save()
开发者ID:octomike,项目名称:Lagerregal,代码行数:57,代码来源:models.py



注:本文中的pystache.render函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pystache.Renderer类代码示例发布时间:2022-05-27
下一篇:
Python pystache.parse函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap