2

I have a field call "scripts" to house scripts like a marketo form script. This gets added in an entry template, but I need to pass this to the layout (if there is something in the field) and render in the footer.

Is this possible? I'm open to ideas or suggestions.

2

Are you on Craft 3 or 2? In 3, you can use the built-in {% js %} ... {% endjs %} tag to inject scripts into tags named {{ endBody() }} or {{ beginBody() }} that you place wherever you like in your layout.

When outputting from the entry, also be sure to use the |raw filter.

https://docs.craftcms.com/v3/dev/tags/js.html

Craft 2 had a similar function: https://docs.craftcms.com/v2/templating/includejs.html

...Or you can just do it all manually with a Twig block - one thing that's a bit annoying about Craft's built-in tags is that they automatically include the <script> tags, which in turn means you won't get JS syntax highlighting in your editor. To do it manually I'd do this:

=========================================
_layout.twig:
=========================================

<html>
<head>
    {{ block('extraHeadData') }}
</head>
<body>
    {{ block('content') }}  
    {{ block('extraFootData') }}
</body>
</html>

=========================================
template.twig:
=========================================

{% extends '_layout' %}

{% block 'content' %}<h1>Hi</h1>{% endblock %}    

{% block extraHeadData %}
    <script>console.log('extra stuff in the head if you really need it');</script>
{% endblock %}

{% block extraFootData %}
    <script>alert('hi');</script>
    {{ entry.scripts ? entry.scripts|raw }}
{% endblock %}

Edit to add: I forgot to mention the one big advantage of using Craft's built-in methods over native Twig blocks is that they can work anywhere in the template regardless of the nesting level or scope of your blocks. For this reason it's usually preferable. (Even if you start with a simple inheritance model where each template @extends the layout, when the site grows and you start using shared intermediary templates to keep the code DRY, you can start running into very fiddly scope issues).

| improve this answer | |
  • I'm on craft 3. Great! thank you so much for the info! – Danielle Frappier Aug 1 '18 at 17:29
  • the {% includeJs %} tag does the same thing in Craft 2 – foamcow Aug 1 '18 at 21:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.