def test_json_script(self): tests = ( # "<", ">" and "&" are quoted inside JSON strings (('&<>', '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>' )), # "<", ">" and "&" are quoted inside JSON objects ({ 'a': '<script>test&ing</script>' }, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>' ), # Lazy strings are quoted (lazystr('&<>'), '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>' ), ({ 'a': lazystr('<script>test&ing</script>') }, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>' ), ) for arg, expected in tests: with self.subTest(arg=arg): self.assertEqual(json_script(arg, 'test_id'), expected)
def sidebar_props(context): request = context["request"] search_areas = admin_search_areas.search_items_for_request(request) if search_areas: search_area = search_areas[0] else: search_area = None account_menu = [ sidebar.LinkMenuItem("account", _("Account"), reverse("wagtailadmin_account"), icon_name="user"), sidebar.LinkMenuItem("logout", _("Log out"), reverse("wagtailadmin_logout"), icon_name="logout"), ] modules = [ sidebar.WagtailBrandingModule(), sidebar.SearchModule(search_area) if search_area else None, sidebar.MainMenuModule(admin_menu.render_component(request), account_menu, request.user), ] modules = [module for module in modules if module is not None] return json_script( { "modules": JSContext().pack(modules), }, element_id="wagtail-sidebar-props", )
def test_json_script_custom_encoder(self): class CustomDjangoJSONEncoder(DjangoJSONEncoder): def encode(self, o): return '{"hello": "world"}' self.assertHTMLEqual( json_script({}, encoder=CustomDjangoJSONEncoder), '<script type="application/json">{"hello": "world"}</script>', )
def planinfo(organization=None, field="pk"): if organization: plans = Plan.objects.choices(organization) else: plans = Plan.objects.filter(public=True) plan_info = { p[field]: p for p in plans.values("pk", "slug", "base_price", "price_per_user", "minimum_users", "annual") } return json_script(plan_info, "_id-planInfo")
def render(self): if self.content_rendering_mode == CONTENT_RENDERING_MODE.html: # Rendered content is equal to content when rendering is set to HTML. rendered_content = self.content elif self.content_rendering_mode == CONTENT_RENDERING_MODE.django_template: # Build renderer if needed. if not hasattr(self, '_renderer'): setattr( self, '_renderer', StringTemplateRenderer(self.content, extra_tags=['flexipages'])) rendered_content = self._renderer.render_template(context=dict( item=self)) elif self.content_rendering_mode == CONTENT_RENDERING_MODE.markdown: rendered_content = mark_safe( markdown2.markdown( self.content, extras=["header-ids", "tables", "fenced-code-blocks"])) elif self.content_rendering_mode == CONTENT_RENDERING_MODE.json: try: json_data = json.loads(self.content) except JSONDecodeError as e: json_data = dict(error=str(e)) pass # Render as script tag containing escaped JSON data. rendered_content = json_script(json_data, 'content_data_%i' % self.pk) elif self.content_rendering_mode == CONTENT_RENDERING_MODE.javascript: rendered_content = format_html('<script>{}</script>', self.content) else: raise ValueError("Unknown rendering mode.") rendered_content = '<a id="item_%s"></a>%s' % (self.pk, rendered_content) rendered_content = mark_safe(rendered_content) edition_context = getattr(self, EDITION_CONTEXT_ATTRIBUTE_NAME, None) if edition_context and edition_context.get(IS_EDITING_ATTRIBUTE_NAME, False): django_engine = engines['django'] template = django_engine.get_template( 'flexipages/edition/item_toolbar.html') rendered_content = template.render( context=dict(edition_context=edition_context, item=self, rendered_content=rendered_content)) return rendered_content
def test_json_script(self): tests = ( # "<", ">" and "&" are quoted inside JSON strings (('&<>', '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>')), # "<", ">" and "&" are quoted inside JSON objects ( {'a': '<script>test&ing</script>'}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>' ), # Lazy strings are quoted (lazystr('&<>'), '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>'), ( {'a': lazystr('<script>test&ing</script>')}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>' ), ) for arg, expected in tests: with self.subTest(arg=arg): self.assertEqual(json_script(arg, 'test_id'), expected)
def page_context(context, element_id, _re_language=re.compile(r'[_-]'), *args, **kwargs): request: HttpRequest = context['request'] user = request.user return json_script( dict(locale=_re_language.split(translation.get_language())[0], user=UserSerializer(instance=user).data, groups=tuple(user.groups.values_list('name', flat=True)), djangoAdminUrl=reverse('admin:index') if user.is_staff else '', logoutUrl=reverse('logout'), languages=[(k, translation.gettext(v)) for k, v in settings.LANGUAGES], version=settings.VERSION, messages=[ dict(text=str(m), type=m.level_tag) for m in get_messages(request) ]), element_id)
def planinfo(organization=None, field="pk"): if organization: plans = Plan.objects.choices(organization, StripeAccounts.muckrock) else: plans = Plan.objects.filter(public=True) plan_info = { p[field]: p for p in plans.values("pk", "slug", "base_price", "price_per_user", "minimum_users", "annual") } # add in free free_info = { "pk": "", "slug": "", "base_price": 0, "price_per_user": 0, "minimum_users": 1, "annual": False, } plan_info[free_info[field]] = free_info return json_script(plan_info, "_id-planInfo")
def test_json_script_without_id(self): self.assertHTMLEqual( json_script({"key": "value"}), '<script type="application/json">{"key": "value"}</script>', )
def test_json_script(inp): json_script(inp, "id")