How to make part of text in a paragraph bold/italic/etc using helper.h functions?

AI-generated summary

The discussion revolves around using Discourse’s helper.h functions to create HTML elements with specific formatting. loginerror is trying to achieve this:

<div>
<p>This text <i>is italic</i> </p>
</div>

Using the h function, and is close with the following code, but it’s not rendering both the text and the italicized part:

html() {
  return [  h('div'),
            h('p', "This text" + h('i', "is italic"))
         ]
}

david explains that the h function parameters are tagName, properties, children, and children can either be a single node or an array of multiple nodes. He provides the correct solution:

h('div',   // <div>
  h('p', [   // <p>
    'This text ',
    h('i', 'is italic')  // <i></i>
  ])  // </p>
);  // </div>

loginerror thanks david and mentions the idea of introducing a simple converter from HTML to h function, which would speed up development. awesomerobot provides a link to a GitHub repository showing an example of using a template with the h function.

Maybe a simple question, but it stopped me for a bit :sweat_smile:

How to achieve this using Discourse helper.h function?

<div>
<p>This text <i>is italic</i> </p>
</div>

The closest I got is this:

    html() {
      return [  h('div'),
                h('p', "This text" + h('i', "is italic"))
             ]
    }

Which returns this:
image

Otherwise, a few other variants I tried either return This text or is italic, but not both :thinking:

For example, this:

    html() {
      return [  h('div'),
                h('p', "This text", [h('i', "is italic")])
             ]
    }

returns just the is italic
image

Almost there?
This:

    html() {
      return [  h('div', ),
                h('p', [h('i', "is italic"), "This text"])
             ]
    }

Gives me this :sweat_smile:

image

The parameters to the h function are tagName, properties, children. You can skip properties if you want, and just use tagName, children. Children can either be a single node, or an array of multiple nodes.

So I think you want something like

h('div',   // <div>
  h('p', [   // <p>
    'This text ',
    h('i', 'is italic')  // <i></i>
  ])  // </p>
);  // </div>
6 Likes

Thank you, I didn’t realize a single node can also be a simple text. This is now quite powerful.

On another note, did to ever consider introducing a simple converter from HTML → h function? This would speed up development a lot at times :slight_smile:

It is possible to use a template like this in some cases

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/app/widgets/embedded-post.js#L11

5 Likes