are you using any frameworks (vue, react or similar) or just plain javascript?
Jan 30, 2023
4
Level 1
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!
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.