def test_paginate(self): """Places Pager object in context with size/num from request.""" from moztrap.model.tags.models import Tag tpl = template.Template( "{% load pagination %}{% paginate queryset as pager %}" "{% for obj in pager.objects %}{{ obj }} {% endfor %}") request = Mock() request.GET = {"pagesize": 3, "pagenumber": 2} for i in range(1, 7): self.F.TagFactory.create(name=str(i)) qs = Tag.objects.all() output = tpl.render( template.Context({ "request": request, "queryset": qs })) self.assertEqual(output, "4 5 6 ")
def test_named_block_noresolve(self): class StartBlock(core.Tag): options = core.Options(arguments.Argument("myarg", resolve=False), blocks=[ BlockDefinition( "nodelist", VariableBlockName( "end_block %(value)s", 'myarg'), "end_block") ]) def render_tag(self, context, myarg, nodelist): return "nodelist:%s;myarg:%s" % (nodelist.render(context), myarg) with TemplateTags(StartBlock): ctx = template.Context() tpl = template.Template("{% start_block 'hello' %}nodelist-content" "{% end_block 'hello' %}") output = tpl.render(ctx) expected_output = 'nodelist:nodelist-content;myarg:hello' self.assertEqual(output, expected_output)
class TestLockStatus(CommentTestCase): def setUp(self): super(TestLockStatus, self).setUp() request = RequestFactory().get('/') self.context = template.Context({ 'request': request, 'user': self.user, 'object': self.content_object, 'ct': self.content_type, 'obj_pk': 1 }) TEMPLATE = template.Template( '{% load comment_tags %}{% get_comment_lock_status for object as status %}{% if status %}YES{% else %}NO{% endif %}' ) def test_locked(self): self.comment_list.lock() tools.assert_equals('YES', self.TEMPLATE.render(self.context)) def test_unlocked(self): tools.assert_equals('NO', self.TEMPLATE.render(self.context))
def test_valid_hotkeys(self): t = template.Template(self.template) c = template.Context() s = t.render(c) self.assertIn(u"var hotkeys = {70: {'link': '/test/'}};", s) # twice the same combination, we consider the last one ks_settings.HOTKEYS.append({'keys': 'f', 'link': '/test2/'}) s = t.render(c) self.assertIn(u"var hotkeys = {70: {'link': '/test2/'}};", s) ks_settings.HOTKEYS.append({'keys': 'n', 'link': '/next/'}) s = t.render(c) self.assertIn( u"var hotkeys = {78: {'link': '/next/'}, 70: {'link': '/test2/'}};", s) # more actions for one combination ks_settings.HOTKEYS = [{ 'keys': 'j', 'js': 'alert(\'J pressed\');', 'link': '/test/' }] s = t.render(c) self.assertIn(u"var hotkeys = {74: {'link': '/test/'}};", s)
def getContextFromTemplateString(site, program, receivers, message_properties, subject, template_string): """Sends out a notification to the specified user using the template string to construct the notification body. Args: site: Site entity. program: Program entity to which the notification applies. receivers: Email addresses to which the notification should be sent. message_properties: Message properties. subject: Subject of notification email. template_string: Template used for generating notification. Returns: A dictionary containing the context for a message to be sent to one or more recipients. """ template_inst = template.Template(template_string) context_instance = template.Context(message_properties) body = template_inst.render(context_instance) return _getContextCommon(site, program, receivers, message_properties, subject, body)
def render(self, context): """Output the content of the `PlaceholdeNode` in the template.""" content = mark_safe(self.get_content_from_context(context)) if not content: return '' if self.parsed: try: t = template.Template(content, name=self.name) content = mark_safe(t.render(context)) except TemplateSyntaxError as error: if global_settings.DEBUG: content = PLACEHOLDER_ERROR % { 'name': self.name, 'error': error, } else: content = '' if self.as_varname is None: return content context[self.as_varname] = content return ''
def display_docx_filefield_as_html(filefield): if not filefield: return '' t = template.Template(""" <div class="alert alert-info" role="alert"> Can't see the application, or the formatting is wonky? <a href="{{ filefield.url }}">Download the application here </a> </div> <div class="well"> {{ html }} </div> """) try: html = convert_docx_filefield_to_html(filefield) except ConversionError: html = 'docx to HTML conversion failed. Try downloading the document instead.' c = template.Context({'filefield': filefield, 'html': html}) return t.render(c)
def render(self, context, instance, placeholder): context.update({ 'placeholder':placeholder, 'object':instance, }) try: if instance.snippet.template: t = template.loader.get_template(instance.snippet.template) context.update({'html': mark_safe(instance.snippet.html)}) content = t.render(Context(context)) else: t = template.Template(instance.snippet.html) content = t.render(Context(context)) except template.TemplateDoesNotExist: content = _('Template %(template)s does not exist.') % {'template': instance.snippet.template} except Exception: exc = sys.exc_info()[0] content = str(exc) context.update({ 'content': mark_safe(content), }) return context
def get(self, request, object_id): model_fields = [f.name for f in self.opts.fields] fields = [f for f in request.GET['fields'].split(',') if f in model_fields] defaults = { "form": self.form, "fields": fields, "formfield_callback": self.formfield_for_dbfield, } form_class = modelform_factory(self.model, **defaults) form = form_class(instance=self.org_obj) helper = FormHelper() helper.form_tag = False helper.include_media = False form.helper = helper s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \ '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>' t = template.Template(s) c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)}) return HttpResponse(t.render(c))
def echarts_js_dependencies(context, *args): dependencies = [] def _add(_x): if _x not in dependencies: dependencies.append(_x) for a in args: if hasattr(a, 'js_dependencies'): for d in a.js_dependencies: _add(d) elif isinstance(a, six.text_type): _add(a) if len(dependencies) > 1: dependencies.remove('echarts') dependencies = ['echarts'] + list(dependencies) links = map(DJANGO_ECHARTS_SETTINGS.host_store.generate_js_link, dependencies) return template.Template('<br/>'.join([ '<script src="{link}"></script>'.format(link=l) for l in links ])).render(context)
def render(self, request): """Renders the object content. """ if self.context is None: self.context = self.get_context() # CACHE template_cache_key = "%s-template-%s-%s" % ( settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.content_type, self.id) obj_template = cache.get(template_cache_key) if obj_template is None: obj_template = self.get_template() cache.set(template_cache_key, obj_template) tags = "" for tag in getattr(settings, "LFC_TAGS", []): tags += "{%% load %s %%}" % tag # Render twice. This makes tags within text / short_text possible. result = render_to_string(obj_template.path, self.context) result = template.Template(tags + " " + result).render(self.context) return result
def setup_compile_dir(compile_dir): """ Setup a directory for Sphinx compilation. We need certain files in place to compile the comments Copy the settings, image extension, and an __init__.py to the appropriate places. The original copy of the ``conf.py`` file, found in the current directory (copy it to comment destination) """ if Site._meta.installed: site = Site.objects.get_current().domain else: site = '' module_dir = os.path.dirname(__file__) ext_dir = os.path.abspath(os.path.join(compile_dir, 'ext')) ensuredir(compile_dir) ensuredir(ext_dir) conf_template_file = os.path.join(module_dir, 'sphinx-conf.py') conf_file = os.path.join(compile_dir, 'conf.py') with file(conf_template_file, 'r') as f: conf_template = template.Template(f.read()) conf = conf_template.render( template.Context({'FULL_MEDIA_URL': settings.MEDIA_URL})) with file(conf_file, 'w') as f: f.write(conf) fn = os.path.join(module_dir, 'images.py') shutil.copyfile(fn, os.path.join(compile_dir, 'ext', 'images.py')) fn = os.path.join(module_dir, '__init__.py') shutil.copyfile(fn, os.path.join(compile_dir, 'ext', '__init__.py'))
def pdfdisplay(html): """Returns `html` with links to PDF Documents replaced with the display of those documents. Since there are templates for displaying PDFs that are used in other contexts, reuse them here by constructing a template string that includes them and rendering it. """ soup = BeautifulSoup(u'<div>{}</div>'.format(html)) links = soup(linktype='document') keys = [] for link in links: key = link.get('id') if key: try: document = Document.objects.get(id=key) except: continue canvas_id = 'pdf_{}'.format(key) pdf_url = document.file.url canvas = '{{% include "catalogue/includes/pdf_display.html" with canvas_id="{}" pdf_url="{}" %}}'.format( canvas_id, pdf_url) link.parent.replace_with(canvas) keys.append((canvas_id, pdf_url)) for canvas_id, pdf_url in keys: script_include = '{{% include "catalogue/includes/pdf_script.html" with canvas_id="{}" pdf_url="{}" %}}'.format( canvas_id, pdf_url) soup.div.append(script_include) html = unicode(soup.div) html = re.sub(r'><\/embed>', ' />', html) return template.Template(html).render(template.Context())
def handle(self, *args, **kwargs): """ Note: this could be batched to thin out the number of requests """ for event in Event.objects.filter(result_of_message=4): conn = TwilioRestClient(account=event.teacher.twilio_account_sid, token=event.teacher.twilio_auth_token) if event.type_of_message == 1: # send sms msg = event.message try: conn.sms.messages.create(to=event.student.phone_number, from_=event.teacher.twilio_number, body=msg[0:160]) event.result_of_message = 0 except: event.result_of_message = 3 print "Sent SMS to " + event.student.phone_number elif event.type_of_message == 2: # send voice call conn.calls.create(to=event.student.phone_number, from_=event.teacher.twilio_number, url='%stwilio_calls/%d/' % (BASE_URL, event.id)) event.result_of_message = 0 print "Called " + event.student.phone_number #actually check result later elif event.type_of_message == 3: # send email message message = template.Template(event.message) c = template.Context({'student': event.student}) send_mail('Message from your teacher', message.render(c), event.teacher.user.email, [event.student.email]) event.result_of_message = 0 else: pass # send email, you know, if we get time event.save()
def test_get_element_data(self): request = self.factory.get("/") t = template.Template("""{% load mote_tags %} {% get_element_data "tests/fleet.xml" as fleet %} <fleet> {% for car in fleet.cars %} <car> <brand>{{ car.brand }}</brand> <model>{{ car.model }}</model> </car> {% endfor %} <value>{{ fleet.value }}</value> </fleet>""") result = t.render( template.Context({ "request": request, "cars": [{ "brand": "Opel", "model": "Astra" }, { "brand": "Ford", "model": "Ikon" }] })) expected = """<fleet> <car> <brand>Opel</brand> <model>Astra</model> </car> <car> <brand>Ford</brand> <model>Ikon</model> </car> <value>100</value> </fleet>""" self.assertHTMLEqual(result, expected)
def test_render_within_structblock(self, get_embed): """ When rendering the value of an EmbedBlock directly in a template (as happens when accessing it as a child of a StructBlock), the proper embed output should be rendered, not the URL. """ get_embed.return_value = Embed(html='<h1>Hello world!</h1>') block = blocks.StructBlock([ ('title', blocks.CharBlock()), ('embed', EmbedBlock()), ]) block_val = block.to_python({'title': 'A test', 'embed': 'http://www.example.com/foo'}) temp = template.Template('embed: {{ self.embed }}') context = template.Context({'self': block_val}) result = temp.render(context) self.assertIn('<h1>Hello world!</h1>', result) # Check that get_embed was called correctly get_embed.assert_any_call('http://www.example.com/foo')
def display_action(form, cnt): action = form["action_name_%d" % cnt] values = [] acnt = 0 verrors = [] while True: try: values += [form["action_arg_%d_%d" % (cnt, acnt)]] if len(form["action_arg_%d_%d" % (cnt, acnt)].errors): verrors += form["action_arg_%d_%d" % (cnt, acnt)].errors acnt += 1 except KeyError: break t = template.Template(""" <div id="action_{{ idx }}" class="item"> {{ afield }}{% for v in values %}{{ v }}{% endfor %}{{ verrors }} </div> """) return t.render(template.Context({ "idx": cnt, "afield": action, "values": values, "verrors": display_errors(verrors) }))
def testTrackBackRDFTemplateTag(self): t = template.Template( "{% load trackback_tags %}{% trackback_rdf object_url object_title trackback_url True %}" ) c = template.Context({ 'trackback_url': '/trackback/blog/pingable-entry/', 'object_url': '/blog/pingable-entry/', 'object_title': 'Pingable Test Entry' }) rendered = t.render(c) link_re = re.compile(r'dc:identifier="(?P<link>[^"]+)"') match = link_re.search(rendered) self.assertTrue(bool(match), 'TrackBack RDF not rendered') self.assertEquals( match.groups('link')[0], 'http://example.com/blog/pingable-entry/', 'TrackBack RDF did not contain a valid target URI') ping_re = re.compile(r'trackback:ping="(?P<link>[^"]+)"') match = ping_re.search(rendered) self.assertTrue(bool(match), 'TrackBack RDF not rendered') self.assertEquals( match.groups('link')[0], 'http://example.com/trackback/blog/pingable-entry/', 'TrackBack RDF did not contain a TrackBack server URI')
def display_condition(form, cnt): target = form["cond_target_%d" % cnt] configure_field_classes(target) operator = form["cond_operator_%d" % cnt] configure_field_classes(operator) value = form["cond_value_%d" % cnt] configure_field_classes(value) t = template.Template(""" <div id="condition_{{ idx }}" class="item"> <div class="col-lg-3 col-md-3 col-sm-3">{{ tfield }}</div> <div class="col-lg-3 col-md-3 col-sm-3">{{ofield}}</div> <div class="col-lg-4 col-md-4 col-sm-4">{{ vfield }}</div> {{ verrors }} </div> """) return t.render( template.Context({ "idx": cnt, "tfield": target, "ofield": operator, "vfield": value, "verrors": display_errors(value.errors) }))
def test_fixed_ga(self): tpl = template.Template(""" {% load opencomparison_tags %} {% fixed_ga %} """) context = template.Context() with SettingsOverride(URCHIN_ID='testid', DEBUG=False): output = tpl.render(context) self.assertTrue( 'var pageTracker = _gat._getTracker("testid");' in output) with SettingsOverride(URCHIN_ID='testid', DEBUG=True): output = tpl.render(context) self.assertEqual(output.strip(), "") with SettingsOverride(URCHIN_ID=None, DEBUG=True): output = tpl.render(context) self.assertEqual(output.strip(), "") with SettingsOverride(URCHIN_ID=None, DEBUG=False): output = tpl.render(context) self.assertEqual(output.strip(), "")
def test_recurse(self): t = template.Template("""{% load recurse %}{% recurse_children %} {% for item in items %}{{ item.value }} {% if item.children %}{% recurse item.children as items %}{% endif %} {% endfor %}{% endrecurse %}""") d = { "items": [{ "value": "root", "children": [{ "value": " leaf1", "children": [{ "value": " leafleaf1" }] }, { "value": " leaf2" }] }] } c = template.Context(d) out = t.render(c) self.assertEqual(out, u'\nroot\n\n leaf1\n\n leafleaf1\n\n\n leaf2\n\n\n')
def test_empty_address_use_defaults(self): # When an empty address is passed uses the EASY_MAPS_CENTER # setting html = "{%% load easy_maps_tags %%}{%% easy_map '%(v)s' 500 500 10 %%}" address = [None] # nonlocal # below we patch the render_to_string in order to retrieve the # map context variable and check its coordinate def get_address_instance(*args, **kwargs): template_name, context = args address[0] = context["map"] return "" t = template.Template(html % {"v": ""}) with mock.patch("classytags.helpers.render_to_string", get_address_instance): t.render(template.Context({})) self.assertEqual(address[0].latitude, AddressTests.fake_default_center[0]) self.assertEqual(address[0].longitude, AddressTests.fake_default_center[1])
def transform(request, syntax_processor_name=None, var_name="text"): """ Returns rendered HTML for source text """ if request.method != 'POST': return HttpResponseNotAllowed("Only POST allowed") source = request.POST.get(var_name) if not source: return HttpResponse('') processor = TextProcessor.objects.get( name=syntax_processor_name or getattr(settings, "DEFAULT_MARKUP", "markdown")) output = processor.convert(source) try: t = template.Template(output, name='markup_preview') output = t.render(template.Context({'MEDIA_URL': settings.MEDIA_URL})) except template.TemplateSyntaxError, e: log.error('Error in preview rendering: %s' % e) output = '<h3 style="color:red">%s</h3><p>%s</p>' % ( ugettext('You have an errors in source text!'), e)
def businessprocess_to_html(process_name, process_type='businessprocess'): bp = adagios.bi.get_business_process(process_name=process_name, process_type=process_type) verbose("Rendering business process %s" % bp.name) c = {} c['bp'] = bp c['csrf_token'] = '' c['graphs_url'] = "graphs.json" c['static'] = True directory = "%s/%s" % (options.destination, bp.name) if not os.path.exists(directory): os.makedirs(directory) if options.graphs: graphs = bi_graphs_to_json(process_name, process_type) for i in graphs: url = i.get('image_url') client = Client() verbose("Saving image %s" % url) image = client.get("/pnp/image?%s&%s" % (url, pnp_parameters)).content graph_filename = "%s/%s.png" % (directory, url) open(graph_filename, 'w').write(image) graph_json_file = "%s/graphs.json" % (directory) for i in graphs: i['image_url'] = i['image_url'] + '.png' graph_json = json.dumps(graphs, indent=4) open(graph_json_file, 'w').write(graph_json) content = open(options.source, 'r').read() t = template.Template(content) c = template.Context(c) html = t.render(c) destination_file = "%s/index.html" % directory open(destination_file, 'w').write(html.encode('utf-8'))
def make_url(url, context=None): if context: url = template.Template(url).render(context) if url.startswith("/"): url = url.replace("/", "", 1) try: if settings.MINIFY_JS: url = MINIFY.sub(".min.js", url) except: pass try: if settings.MINIFY_CSS: url = MINIFY_CSS.sub(".min.css", url) except: pass # we might already have an absolute url, # for instance for a third party image # in which case we'll just use that # otherwise it's a local image and wants the # transformation applying if not URL_RE.match(url): if settings.STATIC_URL.endswith('/') and url.startswith('/'): url = settings.STATIC_URL[:-1] + url else: url = settings.STATIC_URL + url if settings.DEBUG: if not (getattr(settings, 'DEBUG_NO_JS_CACHEBUSTING', False) and \ url.endswith('.js')): if '?' in url: url_separator = '&' else: url_separator = '?' url = url + url_separator + 'cachebust=%s' % str( random.random() * 10) return url
def display_action(form, cnt): action = form["action_name_%d" % cnt] tpl = lib.find_action_template(action.initial) configure_field_classes(action) values = [] verrors = [] for pos, argtpl in enumerate(tpl.get("args", [])): fieldname = "action_arg_{}_{}".format(cnt, pos) if fieldname not in form.fields: continue field = form[fieldname] configure_field_classes(field) arg = {"field": field} if field.errors: verrors += field.errors if argtpl["type"] == "boolean": arg["checkbox"] = True values += [arg] t = template.Template(""" <div id="action_{{ idx }}" class="item"> <div class="col-sm-4"> {{ afield }} </div> <div class="col-sm-6"> {% for v in values %}{% if v.checkbox %}<div class="checkbox"><label>{{ v.field }} {{ v.field.label }}</label></div>{% else %}{{ v.field }}{% endif %}{% endfor %} {{ verrors }} </div> </div> """) return t.render( template.Context({ "idx": cnt, "afield": action, "values": values, "verrors": display_errors(verrors) }))
def pagination(page, uri, list_rows=10): # 显示分页 def gen_page_list(current_page=1, total_page=1, list_rows=10): if total_page <= list_rows: return range(1, total_page + 1) elif current_page <= (list_rows // 2): return range(1, list_rows + 1) elif current_page >= (total_page - list_rows // 2): return range(total_page - list_rows + 1, total_page + 1) else: return range(current_page - list_rows // 2, current_page - list_rows // 2 + list_rows) t = template.Template(''' {% load forum_extras %} {# 如果要使用自定义tag filter这里也需要加载 #} {% if page and page.pages > 1 %} <ul> <li {% ifequal page.index page.prev %}class="disabled"{% endifequal %}><a href="{% build_uri uri 'p' page.prev %}">«</a></li> {% for p in gen_page_list %} <li {% ifequal page.index p %}class="active"{% endifequal %}> {% ifnotequal page.index p %} <a href="{% build_uri uri 'p' p %}">{{ p }}</a> {% else %} <a href="javascript:;">{{ p }}</a> {% endifnotequal %} </li> {% endfor %} <li {% ifequal page.index page.next %}class="disabled"{% endifequal %}><a href="{% build_uri uri 'p' page.next %}">»</a></li> </ul> {% endif %} ''') c = template.Context( dict(page=page, uri=uri, gen_page_list=gen_page_list(page.index, page.pages, list_rows))) return t.render(c)
def test_use_address_instance(self): """It's possible to pass directly to the easy_map tag an Address instance. This test checks also that the database is not hit. """ # create a fake address Address.objects.create(address='fake') n_addresses_before = len(Address.objects.all()) simple_template_string = """{% load easy_maps_tags %} {% easy_map address 500 500 10 %} """ address = Address.objects.all()[0] t = template.Template(simple_template_string) # this assert works only from django1.3 ctx = template.Context({ 'address': address, }) self.assertNumQueries(0, lambda: t.render(ctx)) n_addresses_after = len(Address.objects.all()) # no Address is created in the process self.assertEqual(n_addresses_after, n_addresses_before)
class TagsTest(TestCase): def setUp(self): self.client = Client() def test_unsubscribe_tag(self): from django.template import TemplateSyntaxError try: tpl = template.Template('{% load subscription %}' '{% unsubscribe_link %}') except TemplateSyntaxError, e: self.assertIn(u'tag requires a single argument', "%s" % e) user = UserFactory() tpl = template.Template('{% load subscription %}' '{% unsubscribe_link user %}') context = template.Context({'user': user}) rendered = tpl.render(context) data_tuple = (user.username, user.email) hashed, data = encode_data(data_tuple) url = reverse('mass_post_office:unsubscribe', kwargs={ 'hashed': hashed, 'data': data }) self.assertIn(url, rendered)
def preview_scribble(request): "Render scribble content or return error information." if not request.user.is_authenticated(): return HttpResponseForbidden() can_edit = request.user.has_perm('scribbler.change_scribble') can_create = request.user.has_perm('scribbler.add_scribble') if not (can_edit or can_create): return HttpResponseForbidden() results = { 'valid': False, 'html': '', } form = PreviewForm(request.POST) if form.is_valid(): results['valid'] = True if hasattr(template, 'engines'): scribbler_template = template.engines['django'].from_string(form.cleaned_data.get('content', '')) else: scribbler_template = template.Template(form.cleaned_data.get('content', '')) context = build_scribble_context(form.instance) results['html'] = scribbler_template.render(context, request) results['variables'] = get_variables(RequestContext(request, context)) else: if hasattr(form, 'exc_info'): exc_type, exc_value, tb = form.exc_info reporter = ExceptionReporter(request, exc_type, exc_value, tb) reporter.get_template_exception_info() results['error'] = reporter.template_info else: # Not sure what to do here results['error'] = { 'message': 'Content is not valid', 'line': '', } content = json.dumps(results, cls=DjangoJSONEncoder, ensure_ascii=False) return HttpResponse(content, content_type='application/json')