mbutterick / pollen-users

please use https://forums.matthewbutterick.com/c/typesetting/ instead
https://forums.matthewbutterick.com/c/typesetting/
52 stars 0 forks source link

Getting attributes from attributes list in `define-tag-function` #61

Closed merriman-xyz closed 4 years ago

merriman-xyz commented 4 years ago

Have been playing with Pollen for a bit and after the basics have been trying more advanced features.

Currently I am trying to create a section class that creates a <section> tag with an inner <h2> tag that uses the text of the parent section's id.

In other words, take the following Pollen markup:

◊section[#:id "TITLE"]{ }

and output the following HTML:

<section id="TITLE">
  <h2>Title</h2>
</section>

My current attempts have been via define-tag-function. I have been able to nest the h2 tag, but am having trouble accessing the attributes list and grabbing the id for the inner h2 tag there. Ideally I could grad the ID and transform it into title case.

◊(define-tag-function (section attributes elements)
  `(section ,attributes (h2 ???) ,@elements))

Any help would be appreciated!

otherjoel commented 4 years ago

In your section tag function, attributes will contain a list of keys/values. In this case it will be '((id "TITLE")). You can use Racket’s assoc function to grab the things you want out of there. So, for example (first (assoc 'id attributes)). An even easier way would be to use the attr-ref from the txexpr package. (attr-ref attributes 'id) does the same thing as the assoc example above.

#lang racket

(require pollen/tag ; for define-tag-function
         txexpr)    ; for attr-ref

;; ensure the tag function is available to Pollen source files
(provide (all-defined-out)) 

(define-tag-function (section attrs elems)
  (define title (string-titlecase (attr-ref attrs 'id)))
  `(section ,attrs (h2 ,title) ,@elems))
merriman-xyz commented 4 years ago

Thanks @otherjoel for the lucid explanation.

Installed txepr via raco pkg install txexpr and was able to extract the value of the id attribute with ease.

Lovely being able to build components out of a single command.