What are the best practices of storing data for dynamic content in html? - javascript

Basically, I'm creating a simple brochure website that can change contents dynamically using Javascript. Every time the button is clicked, it calls a function in the .js file which inserts it to the html. To do this, I put these data into a variable in the .js file. The problem is that I find the data too large and is cluttering the .js file.
<button class="content-1">
<button class="content-2">
<div class="container">
# change between content 1 and 2
</div>
// in my case there are more than 2 contents
// each content has other contents as well
// the question is where to put these data
let contentOne = [
"a lot of text data",
"a lot of text data",
"a lot of text data"
]
# other code
For now I managed to separate them into another .js file. But I'm just wondering, is there a cleaner way to store and then access these data? Like using YAML ? How do you usually do it ?
For dynamic websites I realize it's usually stored in databases, but how is it for static websites

I would put it in a different file as JSON. Then in your HTML file, you have a function that does a fetch request to get the JSON file from the server.
This does mean that you need a webserver while you are developing. You can use a light-weight one like http-server.
Then, your code does something like this:
function hydrateData() {
return fetch('data.json').then(response => response.json());
}
hydrateData().then(data => {
// the rest of your code that needs the data goes in here
})

Related

How to append html formatted data from node js server to html file in client side?

I'm trying to build a site in plain javascript, node and handlebars that, trough a quote calculator, the user could request a list of several items to the owner of the site.
The data formatted in json such as:
{ "item": "candy", "brand":"delicious candy" }
would be inserted by the user in index.html.
The site then would perform some validations and then send it to the server through the fetch api attached to a event in a button somehow like 'send quote'
app.post('/api', (request, response) => {
let quote = request.body;
response.render('admin', quote);
Then HandleBars would insert the data in html such as:
<h1> Candy </h1>
<h2> Delicious candy </h2>
And here is where I'm stuck, I'm capable to visualize in the console the response of the api call, and apparently is sending back to the browser the data I want, but I cannot wrap my mind in how could I append this HTML to a HTML file called admin.html.
Are you at all familiar with jQuery? What you could do is create an empty paragraph tag in your Handlebars HTML.
<p id="candyData">
</p>
Then, in your JS file where you're adding your event listener for the submit button on your form, query the paragraph by ID.
const candyData = document.querySelector('#candyData');
Now, in your fetch to your server, it could look something like this to get the value to the page.
fetch('/url').then((response) => {
response.json().then((data) => {
if (data.error) {
candyData.textContent = data.error;
} else {
candyData.textContent = data.candyDataObj // candyDataObj should be accessed based on how you're storing the data.
}
});
});
Don't forget to also load in the script tag in your HTML file.
<script src="/scripts/app.js"></script> <!-- the src path should be updated per your directory -->

How to make a page for every single object from JSON data - JavaScript

I've JSON data
[{"name":"Zohir","id":"151232", "code":"ZO"},{"name":"Tuhhin","id":"151233", "code":"TU"}, .....]
I want to show every single object in different page & also i want to render a single student page based on "code", Like www.mylink.com/student/ZO
I don't know is my question correct or not, I'm new in JavaScript
I tried to show all data in a page from JSON file & i did that, but i can't render a single student page
function getStudent() {
fetch('https://myjesondatas123211.herokuapp.com/v/students')
.then((res) => res.json())
.then((data) => {
let output = '<h2>Students</h2>'
data.forEach(function (student) {
output += `
<div class="col-md-4">
<h4>${student.name}</h4>
<p>${student.id}</p>
<p>${student.code}</p>
</div>
`;
});
document.getElementById('output').innerHTML = output;
})
};
A solution to this problem would be fairly complex to create in plain Javascript.
You would need to have an understanding about single page applications and routers to start tackling this problem.
You might want to look over here or search for another tutorial to get the basics:
https://dev.to/rishavs/making-a-single-page-app-in-ye-good-olde-js-es6-3eng
You want to do a single-page app, which is not simple in plain javascript.
You may want to consider using frameworks for this, such as Angular or React to do this quite easily
They have native routers and allow you to create routes with parameters, and display a component depending on this parameter.

Modify theme.liquid using Shopify API

I am looking to add a javascript snippet for some analytics across the store using the Shopify API. I figured out that using admin/themes/:id/assets.json I can modify the theme.liquid to insert snippet but this changes the entire content of the page. The current API call that I do is
admin/themes/35073539/assets.json
{
"asset": {
"key": "layout\/theme.liquid",
"value": "{{content_for_header}}<script>console.log('foo')</script>"
}
}
This obviously doesn't work.
I just want to modify the <head> tag and insert some custom javascript. Also, ScriptTag won't be useful as I have to take some input from user, use that input in my javascript and then insert the snippet. Any help would be appreciated.
First you want to get a list of all assets to make sure you are using the right ID in the Endpoint URL. (the long number before /assets.json)
GET /admin/themes/#{id}/assets.json
Then you want to save a copy of the current file to the server as a backup, just to be safe...
PUT /admin/themes/#{id}/assets.json
{
"asset": {
"key": "layout\/theme.bak.liquid",
"source_key": "layout\/theme.liquid"
}
}
Since the method you are using overwrites the existing file, you need to download the current file, pull the HTML into a javascript variable, modify that HTML, then send the HTML back as you were doing above.
First download theme.liquid....
GET /admin/themes/#{id}/assets.json?asset[key]=layout/theme.liquid&theme_id=828155753
This will return the HTML etc.. for that file, you need to add/change the content of this file and then send that content as you were already ...
PUT /admin/themes/#{id}/assets.json
{
"asset": {
"key": "layout\/theme.liquid",
"value": "*****The HTML FOR THEME.LIQUID"
}
}
And that should do it. If it's successful the code should now be added.
Hope this helps, let me know if you have any questions.

Expression Engine Extension Development - Add custom javascript to rendered entry

I'm working on an extension and one of the options available in the settings needs a custom javascript to be added to the document head when rendered. The problem I am having is with the parsing order. (There may also be a better way of doing the include too)
I am using the channel_entries_tagdata hook.
Inside this, once the settings are processed, I am doing the following:
// Add the required javascript
$jscript = "
<script type="text/javascript">
/*! etc......
</script></head>
";
// Add js
$tagdata = str_replace("</head>", $jscript, $tagdata);
I would like to be able to just keep my javascript in a separate file and include it somehow by reference, but I don't know how to do that at this stage.
The other issue I am running into is the parsing order of the EE variables. Inside the javascript, I am using the variables from the $tagdata. Something like this:
$.post("URL", { channel: "{channel}", entryId: "{entry_id}", urlTitle: "{url_title}", lastSegment: "{last_segment}", editDate: eo.editDate, field: eo.eleName }, function(data){...
How would I call/use the EE variables in this case?
Elaborated...
This extension is for the following:
In the Addons -> Extensions from the control panel, they will activate the extension. In the 'Settings' for that extension, they will be able to authorize, by Channel, the members or groups that can 'edit' entries in that channel.
The extension, after checking permissions, edits each custom field type before it is rendered and wraps it in a class element. The JavaScript file is for this functionality next. When that element is clicked, a modal is opened which will contain the custom field type as well as the channel/entry information, so it can save the field once edited.
Could you let the script in the <head> be a generic function and pass variables to it by calling it from inside your channel entries?
<head>
...
<script>
function W3bGuy_function(channel, entry_id, last_segment) {
...whatever...
}
</script>
</head>
<body>
...
{exp:channel:entries}
some action triggers: W3bGuy_function('{channel}', '{entry_id}', '{segment_3}');
{/exp:channel:entries}
...
channel_entries_tagdata contains the raw template code pulled from within each {exp:channel:entries} loop, and then has another variable ($row) which is an array of the actual data for that entry. (As per the docs.)
So first, you'll have to make sure your entire page template is within your Channel Entries loop if you want to add JS to the <head> in this manner - and that may not work if your <head> is inside an embed.
Second, I'd suggest dumping the $row data that's passed via that hook, to see if you can extract your data in your returned JS from there.
Hope that helps.

Read JavaScript variables from a file with Python

I use some Python scripts on server-side to compile JavaScript files to one file and also add information about these files into database.
For adding the information about the scripts I now have yaml file for each js file with some info inside it looking like this:
title: Script title
alias: script_alias
I would like to throw away yaml that looks redundant here to me if I can read these variables directly from JavaScript that I could place in the very beginning of the file like this:
var title = "Script title";
var alias = "script_alias";
Is it possible to read these variables with Python easily?
Assuming you only want the two lines, and they are at the top of the file...
import re
js = open("yourfile.js", "r").readlines()[:2]
matcher_rex = re.compile(r'^var\s+(?P<varname>\w+)\s+=\s+"(?P<varvalue>[\w\s]+)";?$')
for line in js:
matches = matcher_rex.match(line)
if matches:
name, value = matches.groups()
print name, value
Have you tried storing the variables in a JSON format? Then, both javascript and python can easily parse the data and get the variables.

Categories

Resources