Is it possible to have dynamic assets?

For example:
Someone want to create bootstrap like library and add configuration to *.exs config file or to the database.

config :my_bootstrap, :css_colors,
  label_error: {255, 0, 0}

Is it possible to have dynamic assets?

2 Likes

Sure, you could read in that config in your template eex files and output the appropriate css for example.

You mean something like: my_styles.css.eex or routing to controller to render that file?

Eh you could do that but I would not. I mean putting a <style> element in your layout (which allows changing even per user or so for custom themes) or baking it into a CSS via npm/brunch/etc… to bake it in at asset generation time.

1 Like

@OvermindDL1 Could you please show me an example of this?

I have a block schema that looks something like this:

  schema "blocks" do
    field :template, :string
    field :order, :integer
    embeds_one :style, Ap.CustomField
    embeds_one :content, Ap.CustomField
    embeds_one :options, Ap.CustomField
  end

The embeds_one is used to save jsonb so that each block can have different style editing options. i.e. one block might have the option to edit the color and another might have a background-color option.

{
"id": "f41e2864-a0de-480f-b7a6-96b3c2d1bf66",
"data": {
    "color": "red", 
    "background_image": "/image.jpg"
   }
}

I then just loop over each block in the template:

<%= for block <- @blocks do %>
  <%= render Ap.Themes.Pro.BlockView, block.template,
    conn: @conn,
    block: block %>
<% end %>

I’m currently using webpack to require the block JS if its rendered and I would like to do the same with the styles.

How can I dynamically insert each blocks style into a single element in the head as you mentioned?

Grabbing it from a DB is an entirely different issue from the original in this thread, definitely more dynamic though. ^.^

For something from a DB that could potentially change anytime… Well I’d probably write out values on the elements themselves or write out an entire CSS ‘file’ inline in a <style> tag or so, you will not be able to use webpack for this, just put it in the normal template file, maybe the overall layout one.

Thanks for the reply.

Yeah thats what I was thinking, but I got stuck on how to build out the css from the values in the DB.

I was trying to avoid adding all the CSS inline and thought this SO answer looked promising but it still inserts the styles with the block and not in the head.

I’d just toss in this in the head element of my template:

<script><%= {:safe, @css_from_database} %></script>

Making sure of course the css from the database really is safe, should probably not be directly user editable. :wink:

2 Likes

Cheers! I think that should put me in the right direction.

2 Likes