0

how can I populate a part of or a whole ~H sigil with a variable? I’m trying to use it to insert some existing html table markup into a Liveview page. I tried the following methods, but they result in texts like “#{html_codes}” or “ … ” on the page instead of inserting a table on the Liveview page. If there is a better way to insert arbitrary html codes in a LiveView page, I’m all ears.

html_codes = """
  <table> .... </table>
"""

~H"""
   #{html_codes} or <%= html_codes %>
"""
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
Jason O.
  • 3,168
  • 6
  • 33
  • 72

2 Answers2

2

Received the following tip from the Elixir Slack channel and it worked.

~H"""
<% = Phoenix.HTML.raw(html_codes) %>
"""
Jason O.
  • 3,168
  • 6
  • 33
  • 72
0

You need to do three things:

  1. Make sure the variable you're trying to include itself uses ~H syntax

    html_codes = ~H"""
      <table> .... </table>
    """
    
  2. Make sure the value is in the assigns variable

    assigns = assign(assigns, html_codes: html_codes)
    
  3. In the template, refer to the value using @assign_name syntax

    ~H"""
      <div><p>Here's a table:</p><%= @html_codes %></div>
    """
    

This same syntax should work whether you're in the render/1 callback, a function component, or a separate *.heex file.

David Maze
  • 130,717
  • 29
  • 175
  • 215
  • Thanks, but """ ...
    """" will be brought in from a database, so how do I attach ~H to it?
    – Jason O. Jun 06 '22 at 12:48
  • You could directly call [`Phoenix.LiveView.Helpers.sigil_H/2`](https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.Helpers.html#sigil_H/2), but that would also process any EEx markup inside the untrusted content. I'm not immediately aware of a good way to turn untrusted content into injectable structured HTML. – David Maze Jun 06 '22 at 13:04
  • Thank you for your response. FYI. I added the solution provided on Elixir Slack below. – Jason O. Jun 07 '22 at 14:03