Named Templates for reusable templates


#1

Sometimes we need to repeat some template code inside a template.

Something like that:

<template>
  <ul v-if="display==='inline'">
    <li>Option a</li>
    <li>Option b</li>
    <li>Option c</li>
  </ul>
  <div v-if="display==='dropdown'">
    <button>Click</button>
    <ul>
      <li>Option a</li>
      <li>Option b</li>
      <li>Option c</li>
    </ul>
  </div>
</template>

As you can see, I want to select how to display the ul, but the content of the ul must be exactly the same. If you have to repeat a complex content, or repeate it a lot of times, It can be a headache to mantain all sync.

Right now exist 2 ways to do that.

  • Use string templates, so you can’t use .vue files and have to concatenate your subtemplate where you need it.
  • Using subcomponents, but if you handle too much data & events, is hard to mantain it.

So I suggest to add named templates that can be reusable inside the same component, without using subcomponents, like in that example:

<template>
  <template v-if="display==='inline'" use="my_ul"></template>
  <div v-if="display==='dropdown'">
    <button>Click</button>
    <template use="my_ul"></template>
  </div>
</template>
<template name="my_ul">
  <ul>
    <li>Option a</li>
    <li>Option b</li>
    <li>Option c</li>
  </ul>
</template>

This can be potentially enhanced, but right now I just propose that method to reuse templates inside a .vue file, without extra files or components.
A simple replacing content, if you wish.