Correctly syntax-highlighting javascript in phpstorm - javascript

In an existing laravel application I'm working on, .blade.php files contain a body section with my html and php in it. After the body section they contain a custom_js section which is used for inserting javascript code. In the parent template, the custom_js section is embedded like this:
<script>
#include('custom_js')
</script>
I can't get correct syntax highlighting in my .blade.php files for my javascript code. Php and html is highlighted correctly.
If I put the javascript code inside <script> tags the highlighting works fine and that's how the other developers have worked so far but before deployment you will have to remove these tags or else there would be 2 opening and 2 closing <script> tags. I don't feel comfortable with changing the parent template because that would cause enourmous refactoring effort.
I've already tried setting the Template Data Language of this specific file to various languages but that didn't help.
Is there an easy way or do I have to stick with inserting and removing <script> tags manually before deploying?
I'm using PhpStorm 8.0.3.

The best solution would be
...is to use comment-style language hinting - something like
// #lang JavaScript
someCode();
// #endlang
Something similar is described with language injecting, but I was not able to make this work in this manner :/ - I will update this if I do, I've started a separate question on the generic matter here: How to set syntax highlighting to a code section to a specific language programatically/with comments?
Less prettier way
...is to use Language injections directly - right click the code and click Show context actions (or Alt+Enter) => select Inject language or reference => select language of your choosing, although this does highlight the JavaScript, for me it damages the rest of the file's highlighting partially.
Ugly, but generic working solution
...is to trick PHPStorm in a way it thinks you are actually adding a <script> tag, but in fact you will comment it out.
{!! /* JS syntax highlighter !!}<script>{!! */'' !!}
var following = "javascript";
var doer = () => {
console.log(following);
};
The trick is based of fact that {!! X !!} is actually converted to just <?php echo X; ?> - normally it's a tool for displaying text you don't want to be HTML-escaped.
So the code than becomes
<?php echo /* JS syntax highlighter; ?><script><?php echo */''; ?>
And in the end it just "echos" the empty string.

You need to yield custom_js in the parent blade view.
Like so: #yield('custom_js')
No need to wrap it in script tags.

Wow. I'm really surprised phpstorm can't do the highlighting for you automatically -- in fact, I can't even find an option to force the syntax highlighting which is hugely disappointing since notepad++ can do it with 2 clicks.
My "solution" (it's ugly so I can hardly call it a solution) was to do this:
<script>
...some javascript...
</script>
#include("customJavascript")
<script>
...some javascript...
</script>
and then have open and close script tags in every included blade.php containing javascript fragments. This is really messy though, so I hope someone has a better solution for making code orderly.

If it is still actual:
Just put the tags into your custom_js file and put your code inside. PhpStorm will highlight everything correctly then.

Related

Necessity of <!-- code here //--> block in old jsp file

I am working on some pretty old code and in every jsp file where there is a javaScript block I see some bizarre Syntax. It goes like :
<script language="JavaScript">
<!--
here is the main code (mixed jsp and javaScript)
//-->
</script>
neccesity <!-- code here //-->
I don't find any necessity for <!-- //--> this syntax. But to remove these from the whole project I really have to be sure why these syntax was used.
Does those had any significance previously, I mean for browser issue or something?
Or,
Just a simple mistake which were carried on.?
HTML style comments in javascript date back to a time when not all browsers supported javascript, so would render the code as text. The <script> tag was just assumed to be just like any other unknown tag, so the tag itself was not rendered, but the contents were
I don't think any current browser would have a problem with it, but I would recommend getting rid of it, because who knows what the future will bring
Does those had any significance previously, I mean for browser issue or something?
Yes, it used to. Remember that a script tag embeds non-HTML inside an HTML document, in this case JavaScript code. Since the content of the script tag isn't HTML, but is being parsed by an HTML parser (while it looks for the ending tag), the idea was to use an HTML comment (<!-- ... -->) to contain the JavaScript code, so the HTML parser wouldn't get confused by HTML-like things within the JavaScript code, and so really old browsers that didn't understand script tags at all wouldn't show the "text" inside them.
The one you've quoted is one of many variations.
There's no need, at all, to do this in an HTML document, with modern browsers — or even with really old browsers, at this point.
In an XHTML document, you do need to do something, but what's shown there is likely to be insufficient; you'd need a CDATA section instead.
Assuming you're writing HTML5 documents (<!doctype html>), you can remove those comments from the JSPs.
As stated here: http://www.w3schools.com/tags/tag_comment.asp
You can also use the comment tag to "hide" scripts from browsers without support for scripts (so they don't show them as plain text)
Nowadays not really an issue I suppose. But may not be the best idea to get rid of them.
Those are comments, just removed if no documentation comments are there
Back in the days there were all sorts of tricks used to make sure that the content looked decent even if the user had javascript or cookies disabled.
This looks like it was meant for hiding the javascript, if the browser didn't understand Javascript.

Zend 1.11. headScript()->captureStart() content should be included last

we are working on a Zend 1.11. based application.
In the overall layout, we use
$this->inlineScript()->appendFile(...)
to add all required global libraries such as jQuery.
In some individual views, we need local JavaScripts we included via
<?php $this->inlineScript()->captureStart(); ?>
jQuery(document).ready((function() {
alert('ping');
}));
<?php $this->inlineScript()->captureEnd(); ?>
Here the problem is: The layout file is processed after the view, thus the captured content is obove the library include in the inlineScript stack. As a result, in the html, we get them printed in a way that jQuery is not loaded before our view specific script:
<script type="text/javascript">
//<!--
jQuery(document).ready((function() {
alert('ping');
}));
//-->
</script>
<script type="text/javascript" src="http://.../js/jquery/jquery-1.11.2.min.js"></script>
We did not found any solution browsing the Zend code to let the HeadScript helper print the includes first and the inline script afterwards. Does anybody know how to get this working (first including the script references and printing inline scripts afterwards)?
Thanks a lot
Ben
Aha, I should have checked the first code sample a bit more closely. In your layout you have:
$this->inlineScript()->appendFile(...)
you then said you wanted a solution to "let the HeadScript helper print the includes first and the inline script afterwards". But you aren't using the head script helper at the moment (at least none of the code in your question is).
The call in your layout should be:
$this->headScript()->appendFile(...)
and you will need a corresponding call to echo the result of the head script helper (within the <head>...</head> part of your layout). There are several examples in the documentation if you need to see how this should look.
Then you can leave the rest of your inline script calls as-is, and it shoudl all work fine.
I know the question is very old, but since i did not find any answer here or elswhere, i wanted to share my solution to the problem, it may maybe help someone else having the exact same problem.
Was looking for a answer myself
We are using ZendX_JQuery View Helpers (ZendX_JQuery_View_Helper_JQuery) to include jquery ($this->jQuery() on layout)
it has some nice functions to add JS-Files, but also scripts to the HEAD after the jquery was included, no mather if calling those after or before che inclusion of the jquery js-file itself.
Resolution of your specific problem would be:
<?php
$this->jQuery()->javascriptCaptureStart();
echo <<<JS
$(document).ready(function() {
alert('ping');
});
JS;
$this->jQuery()->javascriptCaptureEnd();

Templating HTML with hidden state instead of comment or custom script tag

Javascript best practices & conventions, such as those emphasized by John Resig and by Nicholas Zachas, author of book Maintainable JavaScript, suggest using HTML comments or script tags with a custom type to store HTML templates.
Comment example:
<div id="myTemplate">
<!-- <ul><li>$item</li></ul> -->
</div>
<script>
var myTemplate = document.getElementById('myTemplate').childNodes[0].data;
var myHtml = myTemplate.replace(/\$item/g, itemValue);
</script>
Script tag example:
<script id="myTemplate" type="text/x-html-template">
<ul><li>$item</li></ul>
</script>
<script>
var myTemplate = document.getElementById('myTemplate').innerHTML;
var myHtml = myTemplate.replace(/\$item/g, itemValue);
</script>
I strongly dislike the comment-based templating because comments are supposed to be just that--comments, intended to be ignored by the functioning application--and as such I'm a little bewildered as to how it even gets to be suggested by JS gurus.
The script tag templating makes a lot more sense, and I'd normally call it a best if not wonderful practice because the purpose and initial non-function are well-delineated. My only issue is that in some modern editors the color highlighting, autocompletion, auto markup validation, etc., are all lost while working within the script tag.
An approach to templating I've taken in the past is to put it all in a container div, then classify the container div as class="template", then in CSS mark it as ".template { display: none; }".
<div id="myTemplate" class="template">
<ul><li>$item</li></ul>
</div>
<script>
var myTemplate = document.getElementById('myTemplate').innerHTML;
var myHtml = myTemplate.replace(/\$item/g, itemValue);
</script>
This has worked fine for me, although the DOM parser and renderer obviously processes the data up front unnecessarily, but I'm not sure whether this is really all that big of an issue or not, as long as the templating constructs do not break HTML validity rules.
My question, then, is, what am I missing? Is the only reason why this third approach to storing template markup--that is, putting it in the DOM as display:none--is discouraged because the DOM parser and renderer will process it anyway? Or are there other reasons, perhaps technical, that I haven't come across yet? I'd like to know because, again, I want to take advantage of my editor's ability to help me fine tune a proper HTML template.
I think that the best method is using the <script> tag. But for your editor,
it must has a solution to add HTML support into the <script> tag with type="html/template-something" too.
For example I code in Sublime Text, and when I want to write a script template tag,
my editor showed me something like this:
As you see, the h1 tag inside the script tag, is different from real h1 in my HTML.
So I search on the internet, and find a solution: finding a file name called HTML.tmLanguage and make this changes:
// change this line
<string>(?:^\s+)?(<)((?i:script))\b(?![^>]*/>)</string>
// to this line
<string>(?:^\s+)?(<)((?i:script))\b(?!([^>]*text/template[^>]*|[^>]*/>))</string>
And after that, I get this result in my editor:
I'm sure there must be a solution for your editor.
Visual Studio 2012
In Visual Studio 2012, if you use the script like this:
<script id="myTemplate" type="text/html">
it will parse the content within it as HTML.
display: none;
Your last solutions, using display: none isn't good, because Search Engines will index the content within it, see this:
Is hidden content (display: none;) -indexed- by search engines?
That unnecessary parsing is why the script tag method is used.
Stating some type other than JS makes the browser ignore that block entirely. Thus, you save processing time and memory. But you might think "Surely users have powerful machines". Not necessarily.
Page performance is a lot slower on mobile, than on the desktop. Mobile has limited memory and processing power. So parsing that hidden block of HTML is unnecessary.
Also, you'll never know what's in the template. It could contain tables with 10k rows. Scripts run in those hidden blocks. It could contain heavy scripts that may contain blocking elements like synchronous XHRs or loops that run 100k times. Who knows!
Additionally, you'd be creating DOM elements and getting them as strings. Why not make them strings in the first place? Skip the DOM building part.
They are templates, you should be running them as needed, not unnecessarily. Unless you know what's inside those hidden tags of yours, then sure, why not? But releasing to the public or making it a generic guideline, I'd stick to the safer method.

Why use "//-->" in javascript

I've seen this tag used after javascript functions for over a decade now and never asked WHY. It's seen in most of the tutorials I've seen over this time, but I usually leave it out... it doesn't seem to have an effect one way or another. Can anyone enlighten me as to why this is used?
If it's just to signify the end of a javascript function, wouldn't the right brace be adequate? If it's for a series of functions, the ending script tag is used.
I doubt I need an example, but for all the other readers out there that are also wondering what it's for, here's some code:
function helloWorld() {
document.write('Hello World');
}
//-->
Thanks in advance!
It's a holdover from the days when browsers without JS support were reasonably common. If you were including JS code directly in an HTML file, you'd include HTML comment tags (<!-- -->) around the code so those browsers didn't display it as part of the page. The reason for // --> is so that browsers that do support JS didn't try to interpret the closing HTML comment as part of the JS code.
Back in the days, some browsers did not handle javascript so to avoid errors, you'd put the javascript code inside an HTML comment block "".
Today, the XHTML standards says you should escape your script like
<script type="text/javascript">
<![CDATA[
... unescaped script content ...
]]>
</script>
You don't have to do that for HTML. Refer to:
http://www.w3.org/TR/xhtml1/
http://www.w3schools.com/tags/tag_script.asp
It's to comment out the code, so legacy browsers that don't support JS won't see it.
That's probably pretty much useless nowadays.
Note that it also needs a <!-- in the beginning to make it a comment.
Read this: http://lachy.id.au/log/2005/05/script-comments
If you notice, you can also usually see a <!-- before the scripts.
That syntax is used so browser that don't support Javascript will ignore the body of those scripts.
In fact, in html, anything surrounded by <!-- and --> is considered to be a comment
It's also useful if you're validating your html code, so the js doesn't appear as invalid html markup. As everyone mentioned however, it's fairly obsolete. I personally try never to have inline javascript, always in an external file that can be cached, which makes this style of coding useless
For browsers that do not understand JavaScript or if JavaScript is manually turned off these start <!-- and end html_comment_tags --> will help the bad_data inside the script > / ? < & ^ % # ) ! - ( to be commented out
If a browser understands javascripts it will not parse the last comment_ending tag--> due to the // placed before the html_comment_end tag--> and if the browser does not understand the meaning of // comment tags of javascript(simply because jscript is turned off) then it obviously parses the --> in the usual way and comments out everything inside the <script></script> including the //

Best approach for including bits of Javascript on individual pages in Sitefinity

Frequently, I just want to drop a bit of jQuery on an individual page. Given my early understanding of Sitefinity, I think...
I can't easily put JS in the <head>.
I could put JS in a Generic Content control, but then my JS is sitting inline in the <body>. Maybe I need to relax, but I don't usually like to put much JS in the <body>.
It feels like this kind of scenario is an afterthought. Is JS a 2nd-class citizen in Sitefinity?
JavaScript does not live in the head. Yahoo even says it is better for performance
I agree with epascarello you really shouldn't be putting your javascript in the head anyway.
And just in case you didn't know about this the jQuery framework is part of Sitefinity. The article also shows you how you can include external libraries in sitefinity from anywhere withing your project whether it be master page or user control.
Why not have the jQuery code in a separate .js file and use unobtrusive JavaScript? With jQuery you can separate behavior and markup so nicely that you should never have to include JavaScript in your head or body ever again.
Just use the standard onLoad function in jQuery and put all of your initialization code in there.
Try it, I think that you will like it! If you like using CSS for separation of presentation and markup, then jQuery can do the same thing with behavior and markup.
This is an old question, but one way you can do it now is:
Add a Javascript block (under Scripts & Styles), and then paste the URL to the jquery code:
http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js
Then add another Javascript block with your jquery, like:
$(document).ready(function() {
alert("hello");
});
Or you can also paste the URL to your js file.

Categories

Resources