In this article, we will see how to bind text, html code and html attributes in our Svelte project.
Text Binding in Svelte
To bind text in Svelte we just have to use the put the variable inside the curly braces { variable } .
Example, we have variable name myName with a value and we want to bind it in our html code.
<script>
let myName ="Robert";
</script>
<main>
<h1>Hello { myName } </h1>
</main>
HTML binding in Svelte
To bind HTML code in our Svelte application we have to use the @html prefix before it.
For example:
<script>
let myHtml ="<h1>My Svelt Project</h1>";
</script>
<main>
{ @html myHtml }
</main>
Result:
Note: Rendering html code using
@html
prefix might lead to a cross-site scripting attacks on your site. So only render code that you trust.
Attribute binding in Svelte
We can also bind attributes in out HTML elements using the curly braces in Svelte.
For example, we want to bind an id to our div, then
<script>
let firstId = "first-div"
</script>
<main>
<div id={firstId}>
This id a div
</div>
</main>
We can also use shorthand form if the attribute name and the value is same. For example
<script>
let id = "first-div"
</script>
<main>
<div {id}>
This id a div
</div>
</main>
Since the attribute is id and the variable name inside the <script>
tag is same .i.e id, we can just use the id inside the { }
bracket.
Once rendered it will be shown an id attribute in html code.
We can also bind boolean value in our code too.
<script>
let foo = true
</script>
<main>
<div>
<button disabled={foo}>Submit</button>
</div>
</main>
Since we have set boolean (foo) to true
and bind it with the button disabled
attribute , so now the button will be disbaled on our html page when rendered.
Result:
Related Articles: