Tyxml - Inserting script tags?

Heya!

I’m trying to understand the syntax for inserting javascript into tyxml template engine? I want to insert a script like this

<script>
       document.body.addEventListener('htmx:configRequest', (event) => { \
        event.detail.headers['X-CSRFToken'] = 'MYTOKEN'; });
</script>

Can’t for the life of me figure out how it’s supposed to be done.

Does script (txt {|...|}) not work?

Eg tyxml/examples/basic_website/site_html.ml at 06b5c2afb4318eaea813151b2a0047212a0c277f · ocsigen/tyxml · GitHub

Not really, testing


let my_function =
  let open Tyxml.Html in
  script
    []
    (txt
       "document.body.addEventListener('htmx:configRequest', (event) => {event.detail.headers['X-CSRFToken'] = 'tokentobeaddedasarg';")

Gives the incomprehensible error

This expression has type 'a list_wrap but an expression was expected of type
  ([< Html_types.script_content_fun ] as 'b) elt = 'b elt

Tyxml attributes are given with an optional named argument ~a:.... If you omit the name it thinks that you’re trying to pass in an empty list of children elements, hence the type error. Just completely omit the attribute list if it’s empty.

Great, now it’s compiling, thanks!

However it escapes the => and turns it into =&gt

Use Unsafe.data instead of txt: tyxml/lib/html_sigs.mli at 06b5c2afb4318eaea813151b2a0047212a0c277f · ocsigen/tyxml · GitHub

Great that worked, thank you so much!

1 Like