Does javascript have a method for having html on multiple lines without appending \ to the end of every line:
alert('\
<a>hello</a>\
<div>world</div>\
');
This is really irritating and escaping all the single quotations is even more irritating.
PHP offers
$variable = <<<XYZ
<html>
<body>
</body>
</html>
XYZ;
Normally I would just keep the html in a separate file and use jquery .load() to get it.
But this project im working on is going to be offline and in a single file so thats a no go.
I would recommend just putting the HTML into a hidden div:
<div id="my_html" style="display:none;">
<a>hello</a>
<div>world</div>
</div>
Then on page load set the variable:
var my_html = "";
$(function() {
my_html = $('#my_html').html();
});
above code assumes you're using jQuery.
The answer is "No", as per the comments above.
But a workaround I've used from time to time is to create the HTML (or other string or data that is easier to create without JS escaping) in a temporary file where I can format it as required while I work on it with nice indenting, extra blank lines for grouping or whatever, and then use a find-and-replace to escape any quotes and do something about the linebreaks (your choice of inserting \ at the end of each line, wrapping each line with "..." +, or just removing all linebreaks) such that the resulting string is safe to copy and paste directly into my JavaScript source code. Once it's in the JS source I would then abandon the temporary file and do any further edits directly in the JS, though obviously you could save the file if you're willing to do the find-and-replace and copy-paste every time something changes.
(Actually you don't need the temporary file at all if you don't care about keeping the non-JSified text, because most editors that you're likely to use for coding will have a find-and-replace that works on a selection.)
You could still have it in a separate file as you used to do and have a compile step to create just one file.
You could load the file using RequireJS and the text! plugin, and use r.js to compile the js/text/html files to one js file. After that, you can include the js content into the html itself...
Related
I am using laravel, vuejs.
Its a simple question. But i need to know if it works before creating it. So what i am currently doing is
I have a WYSIWYG editor. I am saving the content from it into a html file and i am storing the location to that html file as a reference in my database
When the user requests a page, I am retrieving that html file and send the content to the page and place the content in the page.
Now to the question, I need to place adsense code between some contents in the html piece(returned from the server). The html is a whole content returned from the php server. Right?
So how can i place adsense code between each paragraph or so after the content is returned from server?
You should really consider storing content in a DB. But if you really need to store HTML in files for some reason, you can use HTML tags like !adsense! in your editor. Then just read HTML from a file and use str_replace or similar function to replace this tag with actual ad code.
As Alexey said, you may consider storing the content on the DB.
Also, you could consider actually using markdown instead of HTML, you could still use the WYSIWYG, but is easier to pre process it and easy to convert to HTML.
That being said, I second that the best option is to either use "key" to be replaced after, but that would mean giving the control to the person who edits if he wants to add the ad or not.
I would actually think you should pre process that HTML, there are some libraries to pre process it or you could use a regular expression, but, bottom line, you read the HTML before you output it, and find out what is a paragraph (depends on how your WYSIWYG is formatting things, this is why I prefer markdown), for example, you could split it in paragraphs based on the P tags or something like that, and then re assemble that, but adding the ad every X paragraphs, that way you can control how and when you put the ad, instead of the person who edits it.
To pre process the HTML you could use something like one of the following options:
Symphony DOM Crawler (recomended): http://symfony.com/doc/current/components/dom_crawler.html
PHP DOM Functions: http://php.net/manual/en/book.dom.php
A PHP HTML Parser Library: https://github.com/paquettg/php-html-parser
Or something similar.
I need to insert a large amount of HTML into the DOM.
My current way of doing this is copy-pasting the HTML I need to insert into a JS file, formatting it such that it's bug-free within the string, and then using insertAdjacentHTML() to insert.
Having a huge, multi-line string of copy-pasted HTML in the JS just feels dirty every time I happen to scroll through it.
The only constraint is that I really want to avoid using libraries if I can.
Better in this case is pretty much a secure implementation that's an improvement in readability.
Even if you don't wish to use a HTML templating tool, you can still include the HTML in a similar manner.
The handlebars.js site includes some examples, such as including the HTML in the .html file itself, selecting the element, and parsing its contents:
You can deliver a template to the browser by including it in a tag.
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
Compile a template in JavaScript by using Handlebars.compile
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
In your case, you could replace the type property in the html to anything obvious, and retrieve the contents by calling document.querySelector("htmlString").innerHTML.
Other options include loading the HTML as a separate file via AJAX, or if you're daring, writing your own transpiler to stick the HTML in the Javascript for you (which is basically what React does with JSX)
One last thing to consider: you will want to ensure that the injected HTML doesn't include any potential XSS vulnerabilities or that any DOM events won't get screwed up as a result of adding the HTML (though using insertAdjacentHTML should prevent events from breaking).
Also, consider looking over this HTML injection code I wrote awhile back to ensure you're avoiding (some but not all) possible pitfalls:
https://github.com/jsweeneydev/HTMLTemplate/blob/master/htmltemplate.js
Good luck!
I'm trying to come up with a purely front-end solution to a common practice.
In the past, I've stored the HTML for reused website elements (like the <nav>, <header>, <footer>, etc.) in a functions.php file, and used php functions to call these things in on multiple pages. This of course makes it easier to make changes site-wide, making my life easier.
However, I don't really want to use PHP (or in the past, ASP) to do this anymore. Does any one know of a clean way to do this in Javascript, jQuery or even Node? To be clear I want to call a function in the HTML (like writeNav(); ) that pulls the HTML for the nav. I'd rather not include <script> tags everywhere, if possible.
One very common solution for "building up a library of chunks of HTML that can be reused elsewhere" is "templating". There are numerous templating libraries to choose from (Underscore even has its own, small, template function), but I'd recommend looking at Handlebars.js first, as it's very robust but also very simple.
Handlebars templates will allow you to store your HTML however you want:
in strings in your .js files,
in <script type='text/handlebars'> tags on your html pages, or
in separate html files that get compiled in to a single JS file
It will also allow you to swap out small pieces of the HTML, so that you could (for instance) have a header that gets used all over, but replaces the title, like so:
<h3>{{title}}</h3>
The Handlebars site (http://handlebarsjs.com/) has an excellent run through; I highly recommend it.
There are also text editors like BBEdit with include support if it's just about organizing how you write your HTML.
I think what you're talking about are html includes.
This is not really a production worthy solution, but gets me through the prototyping phase.
Using jQuery, include this in your $(document).ready() callback:
$(".include").each(function() {
var inc = $(this);
$.ajax({
url : inc.attr("title"),
dataType : 'html',
success : function(data) {
inc.replaceWith(data);
console.log("adding " + inc.attr("title"));
});
Then in the body wherever you want to include an html file, do this:
<div class="include" title="path/to/html/file.html"></div>
All elements (divs, spans, etc) with the "include" attribute will be replaced by the content of the file path in the title attribute.
Note: the entire tag will be replaced in this process.
This is trivial with jQuery, e.g.
function writeP(str){
document.write($('<p />').text(str).get(0));
}
You could then do something like:
<div class="foo">
<script type="text/javascript">writeP('hello');</script>
</div>
...which would result in:
<div class="foo">
<p>hello</p>
</div>
That example is silly, but I believe the mechanism is in the spirit of what it is you're trying to accomplish.
Cheers
I have created a string builder JavaScript object and I'm using it with many different .js files in my project.
Can I create this class in a separate .js file and call it from all the other scripts that instansiate it, just like a C# class file?
Is this possible, or do I continue copying and pasting it into the bottom of every .js file that uses it?
Yes, this should not be a problem. Just include the .js files in the correct order in your html pages.
If you include the file in your main HTML page with your other js, you can then use the "class" as you wish:
<script src="js1.js" type="text/javascript"></script>
<script src="js2.js" type="text/javascript"></script>
In the above example, you can now instantiate a new instance of an object from js1.js with the code in js2.js. To do this with pure javascript, you would have to add the script tag to the DOM, or use AJAX to fetch the script file and eval() it.
// Create a <script> element
var scriptEl = document.createElement("script");
scriptEl.src = "js2.js";
scriptEl.type = "text/javascript";
// Append it to the <head>
document.getElementsByTagName("head")[0].appendChild(scriptEl);
To be perfectly correct, it's not the order of inclusion that matter, but rather the order of executing code. In most cases, Andy's and Segfault's instructions are just fine, but sometimes including the class file before its consumers isn't sufficient. For example, if you use ExtJS and you happen to define your class inside an onReady handler like this:
Ext.onReady(function() {
myClass = ...
}.bind(this));
then it won't get executed by the time your second src file is included into the page and executed.
I know, the example is a bit far-fetched :) but just make sure that your code is executed in the right order, not just included in the right order.
I came across this question and I wanted to add something (which probably wasn't there a few years ago).
Even thought you can add every single script to your "index.html" it's not a very beautiful practice (imho). Especially if you consider that you may want to write a extension (~ framework). You don't want to annoy the user with a bunch of script tags he has to add to his code. What you want is a single line like this:
<script src="yourFramework" (...) />
However, with the use of RequireJS you are able to achieve this. You've the freedom to separate your code and "your user" still don't have to add a novel to his "script section".
There are essentially 2 places to define JavaScript functions in Grails, directly in a element on the GSP, and within a separate javascript source file under /web-app/js (for example, application.js). We have defined a commonly reused javascript function within application.js, but we also need to be able to generate parts of the function dynamically using groovy code. Unfortunately, ${some groovy code} does not appear to be processed within separate javascript source files.
Is the only way to do this by defining the javascript function within a script tag on a GSP page, or is there a more general solution? Obviously we could define the javascript function in a script tag within a template GSP file which would be reused, but there is a lot of push to keep our javascript functions defined all together in one place (i.e. the external javascript source file). This has performance benefits as well (the javascript source files are usually just downloaded once by each client's browser, instead of reloading the same javascript functions within the source of every html page they visit). I have toyed around with the idea of breaking the function up into static and dynamic pieces, putting the static ones in the external source and putting the dynamic ones in the template GSP, then gluing them together, but this seems like an unnecessary hack.
Any ideas?
(edit: It may sound like the idea of dynamically generating parts of a JavaScript function, which is then downloaded once and used over and over again by the client, would be a bad idea. However, the piece which is "dynamic" only changes perhaps once a week or month, and then only very slightly. Mostly we just want this piece generated off the database, even if only once, instead of hard coded.)
An easy solution to keep your JavaScript unobtrusive is to create a JavaScriptController and map its actions "/js/*" by adding this to your UrlMappings.groovy file:
"/js/$action"{
controller = "javascript"
}
then just create an action for each dynamic JS file you want, include in in your layout <HEAD>, and presto, you've got a JS file that you can insert Grails snippets into! :)
Note: I've found that there's currently a bug in Grails that doesn't map file extensions to content-types properly, so you'll need to include <%# page contentType="text/javascript; UTF-8" %> at the top of your view files.
This is a great solution. I would like to offer a suggestion to use somthing other then a mapping of "/js/$action" because this is no longer going to allow you to access you javascript files in /web-app/js/. All your javascript files would have to be moved to a the directory your controller would point to.
I would use something like
"/dynjs/$action"
This way you still can point to files in the /web-app/js/ files with out conflict and enjoy the benifits of gsp tags in javascript files
Please correct me if I'm wrong.
Or this... have a tag/service/dynamic method that lets tags write out their JS+CSS+whatever else, to a "cache" which is used to build the JS+CSS resources by a different controller.
Full concept here: [http://www.anyware.co.uk/2005/2009/01/19/an-idea-to-give-grails-tags-esp/][1]
If you want to use models created by the controller (that rendered HTML page which reference the Javascript in which you intend to use groovy code) in the Javascript code, then you can use this technique:
This technique does not need to change URL mappings and does not require you to create extra controller.
In your view GSP add javascript as follows:
<script type="text/javascript">
<g:render template="/javascript/yourJavascriptFile"/>
</script>
In views folder create a "javascript" folder. And create a file named:
_yourJavascriptFile.gsp
You can not only use all the GSP code in your _yourJavascriptFile.gsp file, but you can also use all the models created in your controller (that is rendering the view).
NOTE: There is nothing special about javascript folder. You can name it anything you want OR use an existing view folder. This is just a matter of organizing and identifying your HTML spitting GSP from Javascript spitting GSPs. Alternatively, you can use some naming conventions like: _something.js.gsp etc.
Name your scripts like this
/wherever/the/js/files/are/thescript.js.gsp
The gsp code inside will be rendered correctly by grails. This works, but I have no idea if it's considered a Good Idea or not.
There is another way - pass in the generated code into a function that expects closures. Those closures is generated by the program of course. The generated code is of course inlined/script-tagged in the gsp page.
it may or may not work depending on the nature of the code being generated. But i suspect it will work, and if it doesnt, minor tweaking to the coding style of your javascript will definitely make it work. Though, if these 'generated' code doesnt change much, this quite overkill imo.