Help evaluating patterns in templates

Hi all. I’d be grateful if somone could point out where i’m going wrong using substrings within the following template, which works except that i cannot get the output to sort by a gsub output.

${template.each(query[[
from index.tag "composer" 
order by string.gsub(_.nameFull, '.*% ','')]], template.new[==[
    * **[[${name}]]** ${_.nameFull:gsub('.*% ','')} ${string.gsub(_.nameFull, '.*% ','')} (born ${string.sub(_.dateBirth, 1, 4)}) 
    ]==])}

Frontmatter of a sample page :

---
dateBirth: '1918-08-25'
nameFull: 'Leonard Bernstein'
tags: conductor, composer, pianist
---

#person 

a snippet of output shows that both gsub formulations (to grab just the surname from fullName) are working in the output. However i can’t work out how to use either of them to sort the output:

Interestingly, if i extract year from dateBirth then the following will get correct chronological sorting:

order by string.sub(_.dateBirth, 1, 4)

No doubt some simple mistake, I hope the above isn’t too convoluted and I hope someone can set me right.

Despite this hiccup, even (or because?) i have no experience with either, I’m finding Lua easier than JavaScript and enjoying having switched to v2.

Thanks @zef and to everyone for the posts here which are very helpful.

If you run the query and select the gsub value, you can see that it is returning the resulting string and some count that I don’t understand (it doesn’t appear to be the number of substitutions, which is what I would expect):

${query[[
from p = index.tag "composer"
select string.gsub(p.nameFull, '.*% ', '')
]]}
values
{Beethoven, 1}
{Bernstein, 1}
{Madetoja, 1}

You can see in the first example of the String API how it is handling the return values.

I suspect it is having trouble sorting those pairs of values. You might try adding a function to string to do what you want and reference that instead:

string.lastWord = function (s)
  match, _ = string.gsub(s, '.*% ', '')
  return match
end
${query[[
from p = index.tag "composer"
order by string.lastWord(p.nameFull)
select string.lastWord(p.nameFull)
]]}
1 Like

aaah, thanks very much for directing me so helpfully. I’ll work through this when i’ve got a moment in the next few days. Much appreciated

1 Like