5

How do I add a custom function call in svelte code? Eg. in the DataTableTest.svelte, I want to add the cellFormatter function and make it call automatically and render the div inside the . Following are code :

ABC.svelte

import DataTableTest from "./DataTableTest.svelte";

let columns = [
    {
      label: "ABC",
      property: "abc"
    },
    {
      label: "Items",
      property: "items"
    },
    {
      label: "cellFormatter",
      formatter: function(rowIndex, rowData) {
          return "<div>" + rowData[rowIndex] + "</div>";
      }
    }
  ];


let data = [
  {
    "abc": "dsaaads",
    "items": "dsadsads",
  }

</script>


<DataTableTest title="Test" {data} {columns} />

DataTableTest.svelte

<script>
  export let title;
  export let data;
  export let columns = [];
</script>

{title}
<table>
  {#if columns}
    <tr>
      {#each columns as c}
        <td>{c.label}</td>
      {/each}
    </tr>
  {/if}
  {#if data}
    <tbody>
      {#each data as d, i}
        <tr>
          {#each columns as c}
            {#if c.formatter}
              <td on:load=c.formatter(i, d)></td>
            {:else}
              <td>
              {@html d[c.property] ? d[c.property] : ''}
              </td>
            {/if}
          {/each}
        </tr>
      {/each}
    </tbody>
  {/if}
</table>

I gave a try with

<td on:load=c.formatter(i, d)></td>

But this does not work? Can someone tell how can I do that here?

2 Answers 2

7

You can use the @html template syntax to achieve this:

{#if c.formatter}
    <td>
    {@html c.formatter(i, d)}
    </td>
{:else}
    <td>
    {@html d[c.property] ? d[c.property] : ''}
    </td>
{/if}
Sign up to request clarification or add additional context in comments.

Comments

1

As @morphyish mentioned, you can use the @html template syntax to insert arbitrary html into the DOM.

This is useful if the html for your table items is dynamically fetched from an API at runtime for example – when your web app is not in control of the generation of that html.

If that's not the case, and your web app is in control of generating the html, then instead of constructing a html string, I would recommend creating separate components and referencing those, utilising the <svelte:component> special element to render the components. That way everything in your table is actually a svelte component rather than some arbitrary html, and you get all the goodies that svelte offers.

Here's an example of something along those lines: https://svelte.dev/repl/e38138607bc445ea95754de83e5e0b8d?version=3.8.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.