简体   繁体   中英

Adding external javascript snippet to a Wagtail page field

My current Wagtail project has a very simple structure with some generic pages that have just a body RichTextField . These are just basic CMS type pages where an editor will edit some content in the rich text editor and publish.

One of the pages (and probably more in time) is a "Help Wanted" page and uses an external javascript snippet from a third-party service that lists current job openings with links to the applications that are hosted by them.

Since adding a <script> tag to the rich text editor simply escapes it and displays only the text value, I added an additional extra_scripts = models.TextField() to my page model along with a corresponding FieldPanel('extra_scripts') to the content panels. This lets a user paste in some arbitrary javascript snippets.

If I include this field value in my template with {{page.extra_scripts}} it just displays the content and does not execute the javascript. Looking through the available wagtailcore_tags I'm not seeing a filter that I should use to execute the content, and when it's used with a {{}} tag, I presume the template engine handles it so that it doesn't execute.

How can I include this field in a template so that the javascript is executed?

I know I can change the field to just be the actual javascript content without the <script> tag, but the snippet also includes some basic HTML elements, and the end users aren't going to intuitively know that they need to manually edit the provided snippet if I only give them a field to paste certain parts of the snippet. I want the end user to be able to just copy/paste the snippet they get and have it work without them needing to understand anything else.

This is a result of the Django template language's auto-escaping behaviour , and can be overridden by adding a |safe filter:

{{ page.extra_scripts|safe }}

Of course, you should only do this if your editorial users are fully trusted, since it will give them the ability to run arbitrary code (including, for example, hijacking the session cookie of a superuser who happens to visit that page).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM