sno2
sno2

Reputation: 4183

Is there a `v-html` equivalent in Svelte?

I have recently taken on Svelte and I have been coding a couple of things with it. I have been just doing

<script>
  let title = "Amazing title"
</script>

<h1>{ title }</h1>

when setting the complete value of an html element to the variable, but I would like to know if there is a better way to accomplish this such as the v-html in Vue JS

<template>
  <h1 v-html="title" />
</template>

<script>
export default {
  data() {
    return {
      title: "Amazing title"
    }
  }
}
</script>

Thanks a ton for all of your help and have a great day!

Upvotes: 1

Views: 894

Answers (2)

Etienne
Etienne

Reputation: 183

You can use {@html variableName}. So instead of <span v-html="rawHTML"></span>, you can do <span>{@html rawHTML}</span>. It is reactive if rawHTML changes.

Upvotes: 4

JHeth
JHeth

Reputation: 8366

There isn't anything built into Svelte that is an HTML attribute providing a directive like Vue to my knowledge. But it's very easy to build your own equivalent directives using actions.

To emulate the functionality of Vue's v-html and v-text you can return an update function that changes innerHTML or innerText in a js file:

// html.js
export function html(node, content) {
node.innerHTML = content
return {
    update(content) {
        node.innerHTML = content
    }
  }
}

Then use it on the element whose contents you want to replace:

<!-- App.svelte -->
<script>
  import { html } from './html.js'
  let content = `<p>Content</p>`
</script>

<p use:html={content} />

Here's a REPL showing a more complete example with a v-text style action as well.

Upvotes: 1

Related Questions