Advice on how to improve a database template

I wanted to collect data from a block's textual content and put it automatically into a database column. The following code is what I came up with in order to get the first URL in the block.

Example block:

* The [Wikipedia project](https://wikipedia.org) was started in ...

Now Add to database (e.g. one called bookmarks) and add a template field called e.g. AutoURL. Paste the following Go/Sprig template code (you can remove the comments .action{- /* ...*/}), but I wanted to document this as I found it very cumbersome to figure this out):

.action{- /*We want to access the first link target in a block, e.g.*/}
.action{- /*"The [wikipedia](https://wikipedia.org) was started in ..."*/}
.action{- /* -> https://wikipedia.org*/}
.action{- $row_id := .id -} 
.action{- /* querySpans is a SiYuan function for safe span queries */}
.action{- /* we only want links, which are spans of type 'textmark a' */}
.action{- $a_spans := querySpans "SELECT * from spans where spans.block_id = '?' and spans.type ='textmark a'" $row_id -}
.action{- /* first, regexReplaceAll are sprig functions */}
.action{- $first_link := first $a_spans -}
.action{if $first_link}
 .action{- /* Obtain markdown link target (regex is naive) */}
 .action{- $target_url := regexReplaceAll `\[(.*)\]\((.*)\)` $first_link.Markdown "${2}" -}
 .action{- /* Remove protocol from url (regex naive) */}
 .action{- $visible_url := regexReplaceAll `[a-z]*://(.*)` $target_url "${1}" -}
 .action{- /* Wrap url so that it will appear as a clickable link. This incantation comes from using the inspector on a real URL database cell. */ -}
 <span class="av__celltext av__celltext--url"  data-type="url" 
	    data-href=".action{$visible_url}">
     <span>.action{- abbrev 50 $visible_url -}</span>
 </span>
.action{end}

Now your AutoURL field should show https://wikipedia.org.

  1. How are folks managing typed blocks in SiYuan? (contact, task, book, ...)
  2. How to do the opposite, i.e. how to get database fields to render within the block text? (paragraph or list blocks, not document blocks as in the attributes panel plugin)

More generally, I am open to all sorts of suggestions both

  • on how to improve this code,
  • and or the worflow to develop these templates. At the moment I am copying and pasting on the template column source, which is cumbersome

EDIT (2024-05-29): use .action{if $first_link} ... .action{end} to prevent an error if there are no links.

    1 Operate
    alvorithm updated this article at 2024-05-30 00:52:00

    Related articles

    Welcome to here!

    Here we can learn from each other how to use SiYuan, give feedback and suggestions, and build SiYuan together.

    Signup About
    Please input reply content ...