Programmatically composing a ~H sigil in LiveView

910 views Asked by At

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 %>
"""
2

There are 2 answers

0
Jason O. On BEST ANSWER

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

~H"""
<% = Phoenix.HTML.raw(html_codes) %>
"""
3
David Maze On

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.