Search code examples
javascriptjsf-2facelets

How include Facelets page as javascript file into Facelets page


I create simple page with messages:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
<f:view locale="#{languageController.locale}"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:ui="http://java.sun.com/jsf/facelets">

    <h:head>
    </h:head>
    <h:body>
        <script type="text/javascript">
            var message = '#{msg.validation_message}';
            var notValidMessage = '#{msg.not_submit_message}';
            var notValidCurrentFormMessage = '#{msg.partial_valid}';
            var hap = 'happiness';
        </script>
    </h:body>
</f:view>
</html>

And I have a JS file for validation form:

function validateForm(formId, elementIds, lang) {
    var valid = validateFields(formId, elementIds, lang);
    if (valid) {        
        return true;
    } else {
        alert(message);
        return false;
    }
}

On Facelets page I include Facelets file as JS file:

<h:outputScript library="js" name="errorNames.xhtml"/>
<h:outputScript library="js" name="validation.js"/>

But it seems that page errorNames.xhtml is not included correctly.

How I can solve my problem?


Solution

  • This construct is absolutely not valid. The <h:outputScript> must point to a physically valid JS file.

    Your best bet is using <ui:include> to include it inline.

    So, a /WEB-INF/includes/script.xhtml (no, no XML prolog, no doctype, no html/head/body and the f:view must go in master template; below code is complete as-is):

    <ui:composition
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:ui="http://java.sun.com/jsf/facelets"
    >
        <h:outputScript>
            var message = '#{msg.validation_message}';
            var notValidMessage = '#{msg.not_submit_message}';
            var notValidCurrentFormMessage = '#{msg.partial_valid}';
            var hap = 'happiness';
        </h:outputScript>
    </ui:composition>
    

    (be aware that this is prone to errors whenever one of those variables contain a special character in JS such as a singlequote, a newline, etc, use if necessary OmniFaces #{of:escapeJS()} to escape JS)

    And in /some.xhtml:

    <ui:include src="/WEB-INF/includes/script.xhtml" />
    <h:outputScript library="js" name="validation.js" />
    

    Unrelated to the concrete problem, the way how you're using resource library is not entirely right. Carefully read What is the JSF resource library for and how should it be used?