Why does the level 2 heading displayed on the right side of the header does not include chapter numbering?

image

I want to display the nearest level 1 heading on the left side of the header and the nearest level 2 heading on the right side of the header. However, why can’t the level 2 heading show the chapter number 2.1? Here is my code.

    header:context {
      
      let headings = query(heading)
      
      let head1 = headings.filter(h => h.level == 1 and h.location().page() <= here().page())
      let h1=none
      if head1.len() != 0{
        h1 = head1.last()
      }
      let head2 =  headings.filter(h => h.level == 2 and h.location().page() <= here().page())
      let h2 = none
      if head2.len() != 0 {
        h2 = head2.last()
      }
      
      if h1 != none or h2 != none {
        let h1number = ""
        if h1 != none{
            h1number = str(counter("chapter").at(h1.location()).first()-1)
        h2number}
        // this is error code,it doesn't get the level2 number
        let h2number = ""
        if h2 != none{
            h2number = str(counter(heading).at(h2.location()).first()) //don't get the level 2 number
        }

        grid(
        columns: (1fr, 1fr),
        align(left, text(size: 9pt, if h1 != none { h1number + h1.body } else { none })),
        align(right, text(size: 9pt, if h2 != none { h2number + h2.body } else { none }))
        )
      

        line(length: 100%, stroke: 0.5pt + rgb("#CCCCCC"))
        
        v(1pt)
      }
    },

without looking too closely at your code, I think you can either use hydra – Typst Universe or get inspiration from its code on how to do this yourself.

If you want to work on your own code: I think there got a stray h2number in there (end of if h1 != none), and the code doesn’t show how counter("chapter") is used, so it’s hard to test. (But you can simply use level 1 headings as chapters, then you don’t need to do this yourself.) Fixing these issues, and maybe looking through Hydra to see what info you can get there, will help us help you.

thx for your reply, I try it. I had imported hydra, but it has no effect on my doc.