This is a very short example, but I was wondering if there is a way of using an xml or html file with html markup instead of including it in the javascript like I do below.
I know there are template libraries out there, but I really just want to do something simple and not involve any libraries other than jQuery.
var description = this.name;
if description == 'full') {
return "<div><textarea cols='50' rows='50'>" + this.value + "</textarea></div>";
} else {
return "<div><textarea cols='50' rows='15'>" + this.value + "</textarea></div>";
};
Thanks
In general, without a template engine you have three options:
a) Adding the template directly into your markup as script tag
<script type="text/template" data-template="stats">
<div id="content">
...
</div>
</script>
The html code inside the script tag could be accessed with the following code:
$("script[data-template=" + templateName + "]").html()
The big benefit of this approach is that you are not making another http request.
b) Putting the template in external file and load it via ajax.
$.ajax({
url: "test.html"
}).done(function(html) {
...
});
c) Doing the things like you already did.
If you use AJAX to call a file, you can use the result of the file, which could be XML or nested HTML, etc etc.
I define a hidden div on my markup - then give it a generic ID, then in javascript I use the jQuery.clone() method to make a clone of that markup, and in the markup I define the template macro values that can then be injected with the real data using .replace..
HTML:
<div id="mytemplate">
Name: {0}
</div>
JS/jQuery:
var clone = $('#mytemplate').clone();
Then perform the replacements on the clone object and simply append to the DOM where desired!
Related
I need to send HTML string inside XML to a POST REST service.
Currently I am using string concatenation to create XML's and HTML's like the following,
var html = " <div style='some style'>... append model data from the response of some services ... </div> ";
html += " <div> ... append model data from the response of some services ...</div> ";
var xml = "<?xml version='1.0' encoding='utf-8'?>";
xml += "<root><data>";
xml += "<![CDATA["+ html +"]]>";
xml += "</data></root>";
return $http.post(url,xml,{headers : {'Content-Type': 'application/atom+xml'}});
It looks really ugly as the real html content is huge. Which is the cleanest way to achieve this except string concatenation?
You can do following:
Put your html code in body tag under any specific tag like div with some id or class (I have used id)
example:
The content of the document......
... append model data from the response of some services ...
... append model data from the response of some services ...
Now in javascript you can do like below:
var html = document.getElementById("parent_div").innerHTML;
alert(html);
using above code you can use your html without writing it in JS code.
Also, you can hide this if you don't want to show it on your page.
I want to create a web widget that can be embedded multiple times on the same page but with different data attribute values so I can display different data according to the data attribute value.
For example, I want to embed mywidget.js file multiple times as follows:
<body>
<div>
<script src="script/mywidget.js" data-sport="soccer" id="widget-soccer">
</script>
</div>
<div>
<script src="script/mywidget.js" data-sport="tennis" id="widget-tennis">
</script>
</div>
</body>
My question is, inside the code in mywidget.js, how do I determine the correct script tag reference and read it's data attribute so I can use that value to fetch the corresponding data from a web service. I am using only jquery and javascript.
I want the widget to be embeddable on other users sites as well so all they do is embed using only the script tag and passing in the desired data attribute value without adding anything extra anywhere they need on their website.
This is not really a very good approach, as it is very inflexible. But given that <script> tags, when not deferred, halt parsing of the document while they execute, the current script tag will be the last in the DOM; so you can get the current sport inside your script by using this:
var sport = $('script').last().data('sport');
However, it would be much better to define a function in your external JavaScript file, and then invoke it when you need to instantiate your widget (EDIT: like in Lee Taylor's answer).
Why don't you do something like:
<head>
<script src="script/mywidget.js"></script>
</head>
<body>
<div><script>createMyWidget({sport : "soccer"} );</div>
<div><script>createMyWidget({sport : "tennis"} );</div>
</body>
I don't think you can. I know it's not that nice, but I would try:
<div><script>sport = "soccer";</script><script src="script/mywidget.js" id="widget-soccer"></script></div>
<div><script>sport = "tennis";</script><script src="script/mywidget.js" id="widget-tennis"></script></div>
and use sport in mywidget.js
Another approach could be that myscript.js is actually a dynamic "page", let's say with php, then you could use src="script/mywidget.js?sport=swimming", and in the php you would print:
sport = "<?php echo addcslashes($_GET['sport'], '"'); ?>";
But even better would be:
<script src="script/mywidget.js"></script>
<div><script>showWidget("soccer");</script></div>
<div><script>showWidget("basketball");</script></div>
I think you can use jQuery to find all script tags with src="script/mywidget.js" or something
$('script[src="script/mywidget.js"]')
And then you'll have an array of scripts tags that you can loop through and access the data property using jQuery's .data() method.
I am searching SoundCloud's API and want to be able to add a song to the page once it is clicked from the search results. I am using Plangular and need to also append the tags for that. However, jQuery doesn't seem to like including Angular tags in the append function.
Here is the Search.js
$.ajax({
type: 'POST',
url: '/api/v1/add_song',
data: songParams,
success: function (newSong) {
$('#latest-posts').append(
"<div class='sc-track' plangular='"
+ newSong.url
+ "'><div class='pull-left'<img ng-src='{{track.artwork_url}}'></div> <h3>{{track.user.username}} - {{track.title}}</h3> <button ng-click='playPause()'>Play/Pause</button><progress ng-click='seek($event)' ng-value='currentTime / duration' > {{ currentTime / duration }} </progress> <br> <a ng-href='"
+ newSong.url
+ "'> View on SoundCloud </a>"
+ "</div>"
)
}
})
I am new to Angular, so I'm sure there is a better way to do this. Any help is greatly appreciated!
If you are using Angular, you shouldn't be using jQuery for the ajax calls. I'd suggest you first learn more about the declarative way Angular works, instead of the imperative way jQuery works. Basically you don't modify elements from the controller directly. What you could do is make an array of posts in a controller: $scope.posts. Then you make an ajax call with $http, and in the callback you add the retrieved post to the $scope.posts e.g. $scope.posts.push(response). In your HTML you do something like this:
<body ng-controller="YourController">
<div class="latest-posts">
<div plangular="post.url" class="post" ng-repeat="post in posts">
...
</div>
</div>
</body>
The post in posts will bind to $scope.posts, and by using the ng-repeat the tags (like plangular) get compiled automatically.
In fact, I barely use jQuery in my apps and I can't even remember giving a div an id. I'd suggest you to follow a good tutorial first and check out this: "Thinking in AngularJS" if I have a jQuery background?
This is not the correct way to append Angular's model values.
You can directly access model values like this. Give it try!
$scope[model_name]
I wrote an ajax program.when i am getting response, at that time i will display
that content in my web page using html tags.
So how can I use html tags in javascript?
A sample data you get from server, and a sample html you want to add would make it easier for people to help you.
The basic steps are
1.Get a reference to the html node you want to put the new data in. There are multiple strategies to get reference to the node. If it has an id, it's most starightforward.
2.set innerHTML property.
eg
var node = document.getElementById("targetNode");
node.innerHTML = "<div>data</div>";
Well... Not much detail so not much of an answer...
Easy way
document.write("<body> <div> this is on my page! </div> </body>
or you can edit the innerhtml of an element to place things inside it
document.getElementById("id").innerHTML = "<div>This is inside my element with id="id" </div>"
Answers the question, no?
Instead of embedding html into javascript, you could make a bunch of predefined javascript functions and then use them outside of the script tags. For example, here's how to display a picture while still using the javascript functions.
<html>
<script type="text/javascript">
function display_message()
{
alert("This is a message.");
};
</script>
<body>
<img src="image.jpg">
<form>
<input type="button" value="Click me!" onclick="display_message()" />
</form>
</body>
</html>
I know this is an old post, but this could be helpful...
Using jquery is great way to combine html elements with script
Note: This would be used in the body, if using it in the be sure to enclose it in
$(document).ready (function(){ YOUR CODE });
// Create an object:
var url = {
link: "https://stackoverflow.com/questions/2834929/how-can-i-use-html-tags-in-javascript"
};
// Display URL object:
$('#panel').html('<a href=' + url.link + '>' + url.link + '</a>');
//Note: the # denotes id, if you want to use a class it would be:
//$('.panel').html('<a href=' + url.link + '>' + url.link + '</a>');
//your html would be: <div id="panel"></div> or whatever you choose ie <p> and so //forth
I have a big chunk of HTML which is a template for some data added using AJAX. I would like to store the chunk in a variable and then do replacements on tokens in it but I don't want to mess up the formatting of the html to get it into a javascript string. Is there a thing like the
<<END
command in perl which will read everything following into a string until it hits the end token?
No, unfortunately, there is no such construct in JavaScript.
You have a few different options, each with its own merits:
String concatenation :
var html = '<div id="something">' +
'<p>Lots of HTML</p>' +
'<p>Lots of HTML</p>' +
'<p>Lots of HTML</p>' +
'</div>';
Escaping the newline:
var html = '<div id="something">\
<p>Lots of HTML</p>\
<p>Lots of HTML</p>\
<p>Lots of HTML</p>\
</div>';
Array joining:
var html = [
'<div id="something">',
'<p>Lots of HTML</p>',
'<p>Lots of HTML</p>',
'<p>Lots of HTML</p>',
'</div>'
].join('');
Storing it in an arbitrary hidden element:
HTML:
<textarea id="template" style="display:none;">
<div id="something">
<p>Lots of HTML</p>
<p>Lots of HTML</p>
<p>Lots of HTML</p>
</div>
</textarea>
JavaScript:
var html = document.getElementById('template').value;
I prefer using <script type="text/html">s or HTML comments but <textarea>s seem to be quite popular.
Using a full-on templating engine such as:
http://embeddedjs.com/
http://jtemplates.tpython.com/
Also see: http://ejohn.org/blog/javascript-micro-templating/
Simply put: no.
Since you're already doing AJAX calls, why not also retrieve the template via AJAX too - probably the simplest way to get it into a JS variable.
The language itself doesn't provide anything for this. I have used EJS (Embedded Javascript Templates) to solve a similar problem in the past, though. It was easy to work with, and uses a programming model that should be familiar to most web programmers.
There's no such thing in vanilla JavaScript. And I don't believe there's an implementation of that statement in jQuery either.
But it should be easy to implement with a simple extension method on the String prototype.
Or you could just implement Jogn Resig's micro templating solution (he's the guy who created and maintains jQuery).