pugemail-templates

Iterating through a variable's characters in pug to style them


I am using email-templates and pug to send some mails. I have a verification code I would like to send out nicely framed, with each character in a box, for instance to do something of this kind:

table(style='border-spacing: 6px')
  tr
    th(style='padding: 4px; border: 0.1em solid #CCC; border-radius: 5px;') A
    th(style='padding: 4px; border: 0.1em solid #CCC; border-radius: 5px;') B
    th(style='padding: 4px; border: 0.1em solid #CCC; border-radius: 5px;') C

I'd like to do this using a loop if possible, knowing that the code to display is passed as {locals: {code: 'ABC'}} to email-templates (and that it has more characters).

Is this possible? The resulting html should be quite simple, to display nicely in all mail clients.

Thanks!


Solution

  • You can use an each loop to iterate through each character in the string, since strings are arrays:

    table(style='border-spacing: 6px')
      tr
        each character in code
          th(style='...') #{character}
    

    However, it should be noted that this isn't semantic HTML and will be confusing for people using assistive technology. Each character in the code isn't a table column heading, and shouldn't be marked up as such.

    Instead, consider using semantic elements and then styling those to look the way you want. A more semantic way to mark this up would be to put the code in a paragraph, with each character in a span. Spans allow you to style each character, but they don't impart any semantic meaning, so it will be interpreted as just a paragraph, which is good.

    section
      h2 Verification Code
      p
        each character in code
          span #{character}