I currently am working on a little app that requests user info from my server and displays them using a special template.
At first, I just hardcoded the little snippet in jQuery:
$("<li><div class='outer'><table><tr><td rowspan=2 class='imgcontainer'><img class='thumb'/></td><td><span class='username'/></td></tr><tr><td><span class='name'/></td></tr></table></div></li>")
I clone it several times.
It's ugly and I want it to have syntax highlighting and whatnot, so it would be better for me to have it in the HTML file itself.
Also, it will make merges easier so somebody can just change a line or two.
Is there a pattern for this? Am I OK putting it in the HTML file that I include this JS in (there's only one), and making it hidden using CSS.
The third option I thought of is just creating a separate HTML file and having jQuery request that from the server to keep it separate. Is this technique used much?
Also, is there any term I can use to describe what I'm doing? (It's harder to ask a question for a concept I don't know the name for)
I gave a similar answer on SO earlier today. What you are looking for is called micro-templates. John Resig posted this on his blog. Essentially you can get a json dataset and apply a template to the data to create html and update the DOM.
Related
Let's say you want to dynamically inject 10 extra posts to a WordPress site's homepage blog roll. The 10 new posts are added after some user interaction. So for this example let's pretend the JSON response of the user interaction is identical to the results of this call:
GET /wp-json/wp/v2/posts?s=awesome
What is the ideal way to add the results into the homepage, but ensuring the new posts use the same HTML as the existing ones?
In my mind it seems like the options are currently:
1- Write a loop in Javascript and write the correct html for the posts inside the loop. But that would complicate things like translations and I already have loop templates in PHP, so feels like duplicating code.
2- Writing a custom endpoint. But from what I understand I'd need to write a new WP_Query() with the search parameters, and then return all the html in a single variable (so no get_template_part() and duplicating code again).
3- A hacky idea I had was to add a hidden empty skeleton of the html of a post somewhere on the site on page load. Then when the time comes, in Javascript run a loop and clone the skeleton each time to inject the relevant post data from the JSON. But this feels nasty to me.
Is there a better way? Or am I misunderstanding a basic concept of the WP REST API?
Your idea #3 sounds a lot like using a templating language like Handlebars, and isn't all that hacky necessarily.
You'd "hide" your HTML template in a script tag and then use Javascript to render it with the data that comes from your Ajax call. See the examples here for a basic idea: http://handlebarsjs.com/
I have a lot of inline javascript, but nothing more then calls to functions such as:
<form id="some_id" style="x" method="post" onsubmit="return someFunction(this);"></form>
or "onchange", "onkeyup". I also have some scripts (not many) written inside <script> tags in html and all of the rest is external. The inside calls just as explicit above are all called to external script functions.
I opted to do this because found it more practical considering many async calls with element insertion and needed listeners to register those changes. This is, $.on("form onsubmit", function(){ would not apply to new elements appended async without a listener.
I'm building new elements in the server side due to my template structure and append them directly on the ajax callback.
My main file.js (external) is sitting at 1832 lines and and my index file which includes file.js has about ~500, ~350 with inline javascript as shown above.
This said:
Would it be considered a huge flaw to leave inline javascript as shown above (yes I know google does that) or could it be considered acceptable even by high standards?
Considering "inline javascript is not kept in cache", what does that mean exactly? Each time the user requests the web page he fetches the whole "onsubmit" in the line above? Or am I missing the meaning of this sentence.
Sorry if the question is vague but I'm quite thinking I had most of my service barely done and don't know if I should go over this or not at all :( thank you very much.
It's really hard to define "huge flaw" so let's just stick to pro's and con's of keeping the code "as-is":
Pro's :
Your current code works : No additional work is needed.
Con's :
Harder to debug : you JS is split on many places, a bug will be harder to track using the browser debug tools.Especially for more experienced JS developers who "expect" (or at least hope) the code to be organised following the good practices, like separating HTML, JS and CSS.
Speed : Your clients have to download and parse the additional JS with each query. If you were able to factorize all these methods calls in the main JS file, this would not be needed.
Modularity : all the methods you are calling from the HTML have to sit in the global namespace. The script you have written will be harder to reuse.
So basically, I would keep the code like this if the website is meant to be developed by you only, won't be used by million people and if you do not hope to reuse any of this code on another project.
If any of these condition is not met, I would refactor the code.
Also, refactoring the code, and learning how to correctly bind handler is a very good exercice if you plan on learning some more javascript.
$('body').on('onsubmit', 'form', function(){});
This will deal with any future changes to the DOM.
I want generate a development tool that I can input code (Such as HTML, CSS and JS) and it will create a preview/result window (like JSFiddle). I will be using it for tutorials in school and need a unique site to do this from (I would love to use CodePen, JS Fiddle or Codecademy... But I can't).
I am able to generate a form that can be processed and shown in an iframe (through PHP where it simply echos the information into a new html file that is shown in the iframe). But this came with problems; I only have a cheap server and won't want to put too much pressure on it so need todo this through JS/jQuery.
Firstly is this possible? And how would I go about doing it (code examples would be great!)?
Thanks in advance (I appologise if I haven't given enough detail but I'm fairly new to this and may just be asking a pointless question (I'm only 15 :/ ) )
Cheers :)
There is a rather impressive project called php.js that will let you parse and execute a subset of PHP code in the browser.
If you want to do it complete on a client/ in browser like jsfiddel do, then you need 2 or more frames.
One is for your code and one is for the output.
If you click on "run", then need to apply your code to the frame. You can do this by accessing the document object of the frame. If you got it, you´ll need to inject your code there. There many examples in the web on how to access a child document object from an frame/iframe.
I have a big chunk of deeply-nested semi-structured JSON and would like to generate HTML from it. At the moment I'm using jQote2, but much of the code inside my templates deals with dynamically finding the next template to render and then calling it. What's a single <xsl:apply-templates> in XSLT takes several lines with JavaScript and jQuote. I dearly miss the pattern matching capabilities of XSLT. Is there any (templating) library in JavaScript that allows me to dynamically decide from the data which template to render?
Here is an example of what I want. Suppose I have a JSON structure like this:
{
items:[
{foo:1, bar:2},
{foo:7, baz:99},
{foo:8, quux:3}
],
curdate:'2010-07-07'
}
I'd like to have a "root" template that renders the curdate field and then renders the items. If an item contains a "bar" field, I want the item to be rendered with a template named "tpl-bar" (or something like that), otherwise a template named "tpl-foo" should be used. Filtering capabilities (like "do not render items that have a quux field") would be a nice-to-have.
I am aware of the JSONT library, however from what I see it's not dynamic enough to accomplish what I described.
If no such library exists, I'm on the verge of giving it a shot myself. But I'm not sure how to do it at the moment. Code examples or general descriptions would help me.
There's also JSLT, from what I remember reading it's a little more advanced than JSONT. I've never actually used it, though. The problem is that these libraries aren't hugely popular and so not a lot of work gets done to improve them and build upon them.
On the plus side, it's open source so if you don't find a feature you want you could attempt to add it yourself.
I wanted to give my users a little piece of JavaScript or HTML code that they could put on their site and show information about them. Kind of like StackOverFlows new feature Flair.
I have an idea of how to code it. I was going to give them some JS with a HTML that had a DIV id="MySite_Info". Then the JS would go to my site and pull some JSON or XML and then fill in the data with a DIV in the HTML I gave them on their site.
Is there a better way to do this? Or any examples online I should follow? Whats the best way to create these javascript snippets? (Not sure what the proper name is)
There are two basic options.
Images (and pictures of text suck)
JavaScript - as you described
The approach I would take would be to:
Dynamically generate the JS using a server side process. This would include data for the user (using a JSON generator to easily produce the data in a suitable format).
Build the badge using standard DOM methods
Find the element with the document id and appendChild the generated badge