#Dynamic HTML block rendering

12 messages · Page 1 of 1 (latest)

dim citrus
#

Heya fellows!

I got two questions regarding rendering dynamic blocks for a CMS.

  1. Would you use the H sigil or another one?
  2. How can you dynamically create tags?
defmodule Cms.Blocks.TextBlock do
  @moduledoc false

  use CmsWeb, :live_component

  alias Cms.Block

  @type t() :: %__MODULE__{
          id: String.t() | nil,
          classes: list(String.t()),
          tag: String.t(),
          content: String.t(),
          display_raw: boolean()
        }

  defstruct [:id, :classes, tag: "span", content: "", display_raw: false]

  defimpl Block do
    alias Cms.Blocks.TextBlock

    def to_html(%TextBlock{} = text_block) do
      assigns = Map.from_struct(text_block)

      ~H"""
      <<%= @tag %>></<%= @tag %>>
      """
    end
  end
end

The error here is, that the H sigil cannot dynamically create the tag based on the given struct.

Would you pattern match on the tag and create the inner contents with a separate function?

dim citrus
#

Dynamic HTML block rendering

pulsar thistle
#

Not sure if there's a better way, but that's at least a way

dim citrus
#

Hmm this doesnt seem to be correct unfortunately :(

#

This is the current code:

defmodule Cms.Blocks.TextBlock do
  @moduledoc false

  alias Cms.Block

  @type t() :: %__MODULE__{
          id: String.t() | nil,
          classes: list(String.t()),
          tag: String.t(),
          content: String.t(),
          display_raw: boolean()
        }

  defstruct [:id, :classes, tag: "span", content: "", display_raw: false]

  defimpl Block do
    use HypeClipsWeb, :live_component

    alias Cms.Blocks.TextBlock

    def to_html(%TextBlock{} = text_block) do
      assigns = Map.from_struct(text_block)

      ~H"""
      <.dynamic_tag name={@tag}><%= @content %></.dynamic_tag>
      """
    end
  end
end
pulsar thistle
#

Sorry what are you expecting?

dim citrus
#

the "static" part should include the tag name as its the case when you do <span>

#

But maybe i missed smth since i didnt displayed it in HTML yet

pulsar thistle
#

But it isn't static, it's being loaded dynamically

#

You can't dynamically create a tag and have it show up in the static part of the liveview, static means it's known at compile time which isn't the case here