Is using PHP if / else as part of bad JS practice?

I am creating a custom template for WordPress, and in a couple of places I used PHP if other expressions like the following example in JS in the footer. It works great, but I wonder if this is considered β€œbad practice,” and if so, what is the best way to handle this?

<script type="text/javascript"> var $submenu = $('.submenu'); // SUBMENU animation <?php if ( in_category('Collection') == false ) { ?> // if not a Collection subpage $('.menu li a').each(function() { if ( $(this).text() == 'Collection' ) { // If is Collection link show submenu on hover $(this).mouseenter(function() { $submenu.slideDown(); }); } else { // else close submenu on hover over other menu links $(this).mouseenter(function() { $submenu.slideUp(); }); } }); $('.nav').mouseleave(function() { // close submenu $submenu.slideUp(); }); <?php } else { ?> // If a Collection subpage always show subnav $submenu.show(); <?php } ?> </script> 
+6
source share
3 answers

Despite the fact that there is nothing wrong with PHP and JavaScript, I personally find it rather inconvenient to read and modify, and also makes it difficult to move this code. For example, if you decide to export this JavaScript to an external file, which has many advantages:

 <script src="myjs.js.php"></script> 

This becomes awkward if your JavaScript needs to know certain values ​​in order to calculate in_category('Collection') , since you need to start using GET parameters (if you are not dependent on session variables that can get quite complex and unpredictable, especially with queries resources):

 <script src="myjs.js.php?random_vars_required=123"></script> 

Another thing to be wary of is that when it has a JavaScript file that changes its contents depending on the server-side logic, you have to be careful that the browser caches (to avoid these problems, this basically means that you have to change the request url for every possible result of the js file). i.e.

 <script src="myjs.js.php?collection=true"></script> <script src="myjs.js.php?collection=false"></script> 

Another drawback is mixing PHP with JS, and you will probably end up duplicating PHP code in many places that go against the DRY principal. This is why the proposed "javascript export data" is a much nicer idea. However, it is best to avoid variables in the global js namespace if possible. Avoiding a global namespace can seem complicated, although if you need to share logic with multiple JavaScript files and don't want to export your variables to the top of each file.

another opportunity

If the logic you are testing is purely logical, and it also focuses on page classification (or sub-region classification), the following is a good way to deal with what you are trying to achieve. This is nice mainly because it holds your PHP and HTML together and your JS is separate.

In any template that you use to create external HTML, you should put the following:

 <?php $classes = array(); if ( in_category('Collection') ) { $classes[] = 'collection'; } $classes = implode(' ', $classes); ?> <!-- obviously you'd render the rest of the html markup I've removed it for simplicity //--> <body class="<?php echo $classes; ?>"></body> 

Then in your JavaScript / jQuery:

 if ( $('body.collection').length ) { /// if collection sub page } else { /// else do otherwise } 

If you do not want to add a class to the body element, you can always define your logical check based on what already exists on one version of the page, and not on another. Although I personally like to keep things clean and resort to such checks when I know that HTML markup will not change in the future.

Almost all browsers that the larger world needs to worry about today support multiple element classes. So this means that even if you have a few things you want to check, if that makes sense, you can put these classes in your html or body tag and use the jQuery Sizzle implementation to find them for you.

+2
source

Building the server side of javascript is probably something that we all did, despite the main arguments in favor of this - namely, that js cannot (easily) be verified (using jsLint) and cannot (easily) be placed in a file .js - it makes no sense to allow the browser to cache only one of two or more possible versions of the script.

You might want to consider tearing down server-side branches for client-side branching, which may make the code more readable, but more importantly, is an intermediate step to my final sentence (carry me):

 var $submenu = $('.submenu'); // SUBMENU animation var isCollection = <?php echo in_category('Collection') ? 'false' : 'true' ?>; if ( !isCollection ) { // if not a Collection subpage $('.menu li a').each(function() { if ( $(this).text() == 'Collection' ) { // If is Collection link show submenu on hover $(this).mouseenter(function() { $submenu.slideDown(); }); } else { // else close submenu on hover over other menu links $(this).mouseenter(function() { $submenu.slideUp(); }); } }); $('.nav').mouseleave(function() { // close submenu $submenu.slideUp(); }); } else { // If a Collection subpage always show subnav $submenu.show(); } 

However , if the logical isCollection can be determined in another way (for example, by examining some aspect of the DOM, such as the data-xxx attribute), then you are cooking with gas. Only one version of the js script is needed; it can be easily checked with jsLint; and if desired, it can be transferred to a .js file.

Of course, you need to set the data-xxx attribute (or something else) elsewhere on the server code (complete with an explanatory comment), which is a possible flaw, but perhaps not a big one.

Maybe not all js will succumb to this approach, but I think there will be an example in the question.

In my opinion, in this case it is a viable path.

+2
source

At least this is not a sign of great code. There are alternatives:

  • Create a JSON object and parse it in JavaScript
  • Dynamic JS file inclusion
  • Just set the conditions:

     if(<?= (int)$mybool ?>) { doSomething(); } 
+1
source

All Articles