1

I have picked up the basics of using TWIG to create my site. I suppose I know how to use {%extend%} {%block%} {%include%} and {%set%}, in the most general sense.

I would like to include a block of code from within another twig file without including the whole file - as opposed to {% include 'file.twig' %}.

I have figured out how to set a variable in file.twig and output it using {{ variable | raw }}. I would like to do that in another file, like you would with using jQuery's .load function.

I swear the twig documentation does not seem to touch on this, it seems like really obvious and basic functionality. I have messed around with various combinations of include, for, with, in and only, colons and commas and whatever | is, and nothing.

alexw
  • 8,468
  • 6
  • 54
  • 86
MikeyB
  • 460
  • 1
  • 6
  • 22

1 Answers1

0

I believe you are looking for horizontal inheritance via the use tag:

The use statement tells Twig to import the blocks defined in blocks.html into the current template (it's like macros, but for blocks)

The confusing part is that by itself, {% use ... won't actually insert the content of the blocks in the referenced template. To do that, you must use the block(...) function:

index.twig

{% use "blocks.twig" %}

{{ block('name') }}

blocks.twig

{% block name %}
    <h1>Alex Weissman</h1>
{% endblock %}

{% block hobby %}
    <p>Blanchin'</p>
{% endblock %}

For a working example, see my TwigFiddle (yes, it's a real thing!): http://twigfiddle.com/jjbfug

alexw
  • 8,468
  • 6
  • 54
  • 86
  • Thanks, took a little bit of figuring to realize I had other names used on the page that were similar, not the same, but still interfering. Slightly different functionality (susceptibility to bugging out) to what I'm used to, but think I've got it, at least in this case. I'm now wondering what the correct syntax is for outputting html code placed in TWIG 'blocks' on the same page? – MikeyB May 02 '16 at 23:02
  • Just use HTML the same way you'd use it anywhere else. – alexw May 03 '16 at 01:26