Documenting HEEx within HEEx

Does anyone have a better way of displaying literal HEEx within HEEx than this:

~H"""
<p>Use the component like so:</p>

<pre>
  &lt;.my_component&gt;
    &lt;p%gt;I'm the inner block!&lt;p&gt;
  &lt;/.my_component&gt;
</pre>
"""

My brain isn’t working very well today and thought I’d just ask.

Thank ya!

Maybe you are looking for slots?

https://hexdocs.pm/phoenix_live_view/Phoenix.Component.html#module-slots

I am not, I want to literally render HEEx syntax for documentation purposes. Usually this is done in @doc:

@doc """
## Example
    <.my_component>
      <p>I'm the inner block!</p>
    </.my_component>
"""

But this special case precludes me from doing this when I need some examples that are written in HEEx themselves. Basically, Phoenix.HTML.raw but for HEEx. (er wait, I mean the opposite of Phoenix.HTML.raw, lol. I’m having trouble expressing this question properly).

I don’t know if that is possible.

But maybe an alternative that you could do is moving the inside heex block outside the other heex?

Something like this:

def render(assigns) do
    heex = """
    <.my_component>
      <p>I'm the inner_block!</p>
    </.my_component>
    """

    assigns = assign(assigns, heex: heex)
    
    ~H"""
    <pre><%= @heex %></pre>
    """
end

You want to render that html as string?

OH! That’s a good idea!

@D4no0: Yes, that’s it! I’m really a bit out of it today and scrambling to get something done.

As mentioned above, one of the easier solution is to use an assign, assigns by default are escaping html for safety reasons.

Otherwise, somewhere in the heex engine module there should be the specific function that escapes html if that is more what you are looking for. I’ve done that successfully with leex before.

1 Like

Assigning a raw string is the path of least resistance for me for now. There is Phoenix.HTML.html_escape but it was really more just “how do I cleanly write some heex within heex without it getting interpolated.” I’m hoping this is a temporary solution.

My XY is that I have a Phoenix Storybook story for a LiveComponent coming from a library that I’m wrapping. Making a proper LiveComponent story is proving to be a pain so I’m just making a storybook page and need to write example within a render function. I need to figure out how to make a story work properly, which I will, but for now I just want to get this thing out the door with some docs :slight_smile:

I think the cleanest solution is to define your own sigil on top of ~H that will define sections that are heex and the ones that are literals, not entirely sure if that is 100% doable but should be the most hack-free way.

I agree but ideally I don’t want to do this at all! It’s a tech-debt solution that I will be paying because it’s something I’ll be running into again soon.

If you ever decide on doing this, I think livebook is the best source of inspiration as the livebook “markdown” is a mix of such things.

1 Like