Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iamarsenibragimov's avatar

Is there a better way to add objects to template from JS?

Hey Laracast!

I used to add dynamic data to the page with js like this but I believe there is a better way to achieve the result. What are your recommendations?

file.done(fileInfo => {
                    uploaded_images.append("<div class='group relative'>" +
                                                "<div class='h-200 w-200 aspect-w-1 aspect-h-1 w-full overflow-hidden rounded-md bg-gray-200 group-hover:opacity-75'>" +
                                                    "<img src='" + fileInfo.cdnUrl + "-/scale_crop/200x200/smart/' class='uc_images h-200 w-200 object-cover object-center cursor-pointer'>"+
                                                "</div>" +
                                            "</div>");
                });

Thank you!

0 likes
4 replies
Sinnbeck's avatar

are you using any frameworks (vue, react or similar) or just plain javascript?

Sinnbeck's avatar

@iamarsenibragimov Then go with what @azimidev suggested. I personally have in the past added the templates I need to the dom inside a script template

Something like

<script type="text/template" id="upload-template">
    <div class="group relative">
        <div class="h-200 w-200 aspect-w-1 aspect-h-1 w-full overflow-hidden rounded-md bg-gray-200 group-hover:opacity-75">
            <img src="{{cdnUrl}}-/scale_crop/200x200/smart/" class="uc_images h-200 w-200 object-cover object-center cursor-pointer">
        </div>
    </div>
</script>

and then in my javascript

var template = document.getElementById('upload-template').innerHTML
1 like
azimidev's avatar
azimidev
Best Answer
Level 55

I would recommend using a JavaScript templating library such as Mustache or Handlebars. They allow you to define a template, and then bind data to it dynamically to generate HTML. This makes your code more readable and maintainable as it separates HTML and JavaScript logic. Example using Mustache:

var template = "<div class='group relative'>" +
                 "<div class='h-200 w-200 aspect-w-1 aspect-h-1 w-full overflow-hidden rounded-md bg-gray-200 group-hover:opacity-75'>" +
                     "<img src='{{cdnUrl}}-/scale_crop/200x200/smart/' class='uc_images h-200 w-200 object-cover object-center cursor-pointer'>" +
                 "</div>" +
             "</div>";

file.done(fileInfo => {
    var html = Mustache.render(template, fileInfo);
    uploaded_images.append(html);
});
1 like

Please or to participate in this conversation.