How to pass variables from child template/view into main template view?

Hi, So I’m very new to Elixir and Phoenix not even sure if this is possible but wanted to know how this can be done if it can be done.

I have my main index HTML or admin HTML which has the following at the bottom

<script type="text/javascript">
                 $(function() {
                     var editor = editormd("editormd", {
                          path : "/js/admin/",
                          readOnly:false,
                     });

                 });
             </script>

I then have the following inside my loaded template/view

<div id="editormd">
                        <%= label f, :content, class: "control-label" %>
                            <%= textarea f, :content, class: "" %>
                                <%= error_tag f, :content %>
                        </div>

I’m using the editormd across different views and I need a way to set read-only var to true or false depending on the template

Maybe something like

<div id="editormd" readonly="true">

then

  var editor = editormd("editormd", {
                              path : "/js/admin/",
                              readOnly:myvar,
                         });

Would pick that up and set the correct setting, it would need to reload as well?

Check if drab library can help you out.

Best regards,

1 Like

Thanks I looked at drab but I feel that might be a bit overkill no? Especially as I’m new to Elixir is there a simpler solution

Have your tried something like

<div id="editormd" data-read-only="false">
 $(function() {
  var TARGET_ID = 'editormd';
  var selector = '#' + TARGET_ID;
  var data = $(selector).data('readOnly'); /* i.e. 'data-read-only' is accessed with 'readOnly' - kebab-case to lower camelCase */
  var readOnly = (typeof data) === 'boolean' ? data : true;
  var config = {
     path : '/js/admin/',
     readOnly: readOnly,
  };
  var editor = editormd(TARGET_ID, config);
});

jQuery.data() - HTML5 data-* Attributes

2 Likes

+1 for data attributes. This is the easiest way to change a JS var from an Elixir view.

Alternatively you can use StimulusJS. It’s a great way to structure your JS code.

If you want to take a look at a non trivial example, have a look at these examples from AlloyCI (JS code, Elixir template code)

The Charts JS controller is used to create a dynamically generated line chart, based on the amount of builds a project has had, and it is used across admin view, and regular user view.

1 Like

Thanks man this is perfect not sure why I didn’t think of this as I have done it before