JSF components not parsed inside <script> block

I had to change <script> ... </script>

in the JSF page and try to evaluate the JSF component inside the script. EL was appreciated, but the tag itself was intact.

What is the reason for this behavior?

Example:

<script type="text/javascript">
    //<![CDATA[
        function doSomething() {
            $('.userNode').droppable({
                activeClass : 'ui-state-active',
                hoverClass : 'ui-state-highlight',
                tolerance : 'intersect',
                drop : function(event, ui) {
                   <h:panelGroup rendered="#{myBean.useThis}">
                     alert("code A");
                   </h:panelGroup>
                   <h:panelGroup rendered="#{!myBean.useThis}">
                     alert("code B");
                   </h:panelGroup>
        }
            });
        };
    //]]>   </script>

      

EL #{!myBean.useThis}

was evaluated true / false, but <h:panelGroup>

was rendered.

Why?

+3


source to share


1 answer


This is because you put it in a CDATA block. Anything inside a CDATA block is considered symbolic and not XML data.

Better not to do this at all. This is bad practice. Place the JS function in your own file .js

. Use JSF / EL only to prepare JavaScript variables that JS functions will request (as a method argument) or access by themselves (in the window area), not to populate parts of the JS functions.

eg.

<h:outputScript>var useThis = #{myBean.useThis};</h:outputScript>
<h:outputScript name="script.js" />

      

function doSomething() {
    $('.userNode').droppable({
        activeClass : 'ui-state-active',
        hoverClass : 'ui-state-highlight',
        tolerance : 'intersect',
        drop : function(event, ui) {
           if (useThis) {
               alert("code A");
           }
           else {
               alert("code B");
           }
        }
    });
}

      



To prevent pollution of the global scope, consider creating a namespace.

<h:outputScript>var my = my||{}; my.useThis = #{myBean.useThis};</h:outputScript>

      

           if (my.useThis) {
               alert("code A");
           }
           else {
               alert("code B");
           }

      

See also:

+3


source







All Articles