guigrpa / docx-templates

Template-based docx report creation
MIT License
904 stars 146 forks source link

Manually insert html #294

Closed zedissime closed 1 year ago

zedissime commented 1 year ago

I was wondering if there was a way to insert HTML in the document.

In my document generator, I've added a method in the additionalJsContext in order to have a custom method accessible. This custom method receive a translation key, search for this translation key in a translation object and return the result. It works well for most of our cases, but we have some translations that are plain HTML (for a basic formatting purpose : list, bold, etc).

Is there a way to wrap the result of my function in order to be interpreted from HTML to altchunk (?) in the template ?

jjhbw commented 1 year ago

Doesn't https://github.com/guigrpa/docx-templates#html do what you want?

zedissime commented 1 year ago

Doesn't https://github.com/guigrpa/docx-templates#html do what you want?

Thank you for your prompt answer ! In fact in my template I'm not able to say if the result of my custom function will be a string containing HTML or not.

For example, in my usecase : image

The method t(translation_key) will look in an object like this:

  {
    disclaimer: {
      en: '<ul><li>Rule 01</li><li>Rule 02</li></ul>',
      fr: '<ul><li>Règle 01</li><li>Règle 02</li></ul>'
    },
    hello: {
      en: 'Hello',
      fr: 'Bonjour !'
    }
  }

I'm not confortable to force my users to add the HTML tag when they are writing their templates, as I should be able to transform the result of this custom method.

jjhbw commented 1 year ago

Ah ok, thanks for clarifying your use case. I'm afraid that's a hard limitation of the library: you need to know whether the result of your command will be HTML or not, or else docx-templates won't know how to embed it in the document's XML tree...

zedissime commented 1 year ago

Hmm sad news. Maybe a work around would be to wrap all my results of the t() function by a <span> like this I would always have an HTML as result ?

jjhbw commented 1 year ago

Yes that sounds like it could work. You would still need to use {HTML t(xyz)} commands everywhere, though.

It seems like you question is answered, so I'll close the issue. You can still reply to it though, but be sure to tag me using @jjhbw .