Functions in templates

I have a template query below and I'd like to call a function that returns the ammount of stars. The sterren() function works fine in a ${sterren(3)} block, but I can't render it within the template query. How do I achieve this?

template query

${template.each(query[[
  from index.tag "page"
  where name:startsWith("projecten/")
  order by created desc limit 5]],
  template.new[==[
    🏛️ ${icoon} [[${name}]] sterren(${aantal})
    ]==]
)}

Function:

function sterren(aantal)
  if aantal == 1 then tekst = "⭐️" end
  if aantal == 2 then tekst = "⭐️⭐️" end
  if aantal == 3 then tekst = "⭐️⭐️⭐️" end
  if aantal == 4 then tekst = "⭐️⭐️⭐️⭐️" end
  if aantal == 5 then tekst = "⭐️⭐️⭐️⭐️⭐️" end
    
  return widget.html(dom.span {    
    tekst
  })
end
type or paste code here

do it and more. No coding is necessary. Install and add "#xxx"

${query[[from index.tag "page"
    select { 
      ["Page #upper"] =  ref,
      Modified = lastModified }
    order by lastModified desc limit 5]] or "No empty pages."}

In your case, ["Test #stars"] should fine

ex:

I'm really enjoy every day this plugin.

Templates are basically a fancy way to concatenate (markdown) strings. They don't really support widgets. However, for what you want to do, you don't need them, this should work (with some bonus reduced code size and support for an infinite number of sterretjes :wink:):

```space-lua
function sterren(aantal)
  return string.rep("⭐️", aantal)
end
```

${template.each(query[[
  from index.tag "page"
  where name:startsWith("projecten/")
  order by created desc limit 5]],
  template.new[==[
    🏛️ ${icoon} [[${name}]] ${sterren(aantal)}
    ]==]
)}
1 Like

tnx @malys . I don't feel comfortable installing this just yet.. I want to grasp my head around silverbullet itself more first. Also, I'm forcing myself to judge if I really-really need this before going the extra mile. Gimme some time :slight_smile:

this is cool! I guess the escape here is that I don't need html for the stars. It gets harder when I want to colorize a column word based on its input. I already build a function to do this anywhere within silverbullet, but (as you'd gues) this doesn't work for tables. Would there be a workaround for this too?

function kleurRood(text)
  return widget.html(dom.span {
    style="background:#7B4760; color: white; padding: 0px 8px; border-radius: 5px;",
    text
  })
end

Like you want but Mr red plugins to colorize table is also awesome.

Unfortunately not right now. In theory markdown allows for using inline HTML, but SilverBullet doesn't properly support it yet (see issue: Support Live Preview for HTML tags · Issue #702 · silverbulletmd/silverbullet · GitHub) when that would be implemented, you could simply put HTML tags in your markdown, but until then, not really.

1 Like