Re: Handling null values

amosso <[email protected]>
Newsgroups gmane.comp.web.freemarker.user
Message-ID <[email protected]>
Hi, if you want to handle null values with FreeMarker you have to modify the
source code of tow methods:
    - freemarker.core.ComparisonExpression.isTrue(Environment env)
    - freemarker.core.DollarVariable.accept(Environment env)

code:

NEXT CODE WILL ALLOW YOU TO INTRODUCE EXPRESSIONS LIKE:
                        <#if my.variable != null>
                               ${my.variable}
                        </#if>
IT MEANS: IF my.variable EXISTS IN MODEL THEN CONTENT WILL BE PRINTED
_______________________________________________________________________________
freemarker.core.ComparisonExpression
   boolean isTrue(Environment env) throws TemplateException {
    	TemplateModel ltm = null;
        TemplateModel rtm = null;
        try {
        	ltm = left.getAsTemplateModel(env);
        }
        catch (InvalidReferenceException exc) {
        	ltm = null;
        }
        try {
        	rtm = right.getAsTemplateModel(env);
        }
        catch (InvalidReferenceException exc) {
        	rtm = null;
        }
        
        if (env != null && env.isClassicCompatible()) {
            if (ltm == null) {
                ltm = TemplateScalarModel.EMPTY_STRING;
            }
            if (rtm == null) {
                rtm = TemplateScalarModel.EMPTY_STRING;
            }
        }
        
        int comp = 0;
        
        if (left.getSource().equals("null")) {
        	if (rtm != null)
        		comp = 1;
        }
        else if (right.getSource().equals("null")) {
        	if (ltm != null)
        		comp = 1;
        }
        else {
	        assertNonNull(ltm, left, env);
	        assertNonNull(rtm, right, env);
	        
	        if(ltm instanceof TemplateNumberModel && rtm instanceof
TemplateNumberModel) { 
	            Number first =
EvaluationUtil.getNumber((TemplateNumberModel)ltm, left, env);
	            Number second =
EvaluationUtil.getNumber((TemplateNumberModel)rtm, right, env);
	            ArithmeticEngine ae = 
	                env != null 
	                    ? env.getArithmeticEngine()
	                    : getTemplate().getArithmeticEngine();
	            comp = ae.compareNumbers(first, second);
	        }
	        else if(ltm instanceof TemplateDateModel && rtm instanceof
TemplateDateModel) {
	            TemplateDateModel ltdm = (TemplateDateModel)ltm;
	            TemplateDateModel rtdm = (TemplateDateModel)rtm;
	            int ltype = ltdm.getDateType();
	            int rtype = rtdm.getDateType();
	            if(ltype != rtype) {
	                throw new TemplateException(
	                    "Can not compare dates of different type. Left date is
of "
	                    + TemplateDateModel.TYPE_NAMES.get(ltype)
	                    + " type, right date is of " 
	                    + TemplateDateModel.TYPE_NAMES.get(rtype) + " type.", 
	                    env);
	            }
	            if(ltype == TemplateDateModel.UNKNOWN) {
	                throw new TemplateException(
	                    "Left date is of UNKNOWN type, and can not be
compared.", env);
	            }
	            if(rtype == TemplateDateModel.UNKNOWN) {
	                throw new TemplateException(
	                    "Right date is of UNKNOWN type, and can not be
compared.", env);
	            }
	            
	            Date first = EvaluationUtil.getDate(ltdm, left, env);
	            Date second = EvaluationUtil.getDate(rtdm, right, env);
	            comp = first.compareTo(second);
	        }
	        else if(ltm instanceof TemplateScalarModel && rtm instanceof
TemplateScalarModel) {
	            if(operation != EQUALS && operation != NOT_EQUALS) {
	                throw new TemplateException("Can not use operator " +
opString + " on string values.", env);
	            }
	            String first =
EvaluationUtil.getString((TemplateScalarModel)ltm, left, env);
	            String second =
EvaluationUtil.getString((TemplateScalarModel)rtm, right, env);
	            comp = env.getCollator().compare(first, second);
	        }
	        else if(ltm instanceof TemplateBooleanModel && rtm instanceof
TemplateBooleanModel) {
	            if(operation != EQUALS && operation != NOT_EQUALS) {
	                throw new TemplateException("Can not use operator " +
opString + " on boolean values.", env);
	            }
	            boolean first = ((TemplateBooleanModel)ltm).getAsBoolean();
	            boolean second = ((TemplateBooleanModel)rtm).getAsBoolean();
	            comp = (first ? 1 : 0) - (second ? 1 : 0);
	        }
	        // Here we handle compatibility issues
	        else if(env.isClassicCompatible()) {
	            String first = left.getStringValue(env);
	            String second = right.getStringValue(env);
	            comp = env.getCollator().compare(first, second);
	        }
	        else {
	            throw new TemplateException(
	                "The only legal comparisons are between two numbers, two
strings, or two dates.\n"
	                + "Left  hand operand is a " + ltm.getClass().getName() +
"\n"
	                + "Right hand operand is a " + rtm.getClass().getName() +
"\n"
	                , env);
	        }
        }
        
        switch (operation) {
            case EQUALS:
                return comp == 0;
            case NOT_EQUALS:
                return comp != 0;
            case LESS_THAN : 
                return comp < 0;
            case GREATER_THAN : 
                return comp > 0;
            case LESS_THAN_EQUALS :
                return comp <= 0;
            case GREATER_THAN_EQUALS :
                return comp >= 0;
            default :
                throw new TemplateException("unknown operation", env);
        }
    }
____________________________________________________________________



NEXT CODE WILL IGNORE UNDEFINED VARIABLES
IT MEANS THAT IF SOME VARIABLE IS NOT DEFINED IN MODEL FREE MARKER WILL
IGNORE IT
_______________________________________________________________________
freemarker.core.DollarVariable: 
	void accept(Environment env) throws TemplateException, IOException {
		String val = null;
		try {
			val = this.escapedExpression.getStringValue(env);
			if (val.trim().length() == 0) {
				val = getSource();
				System.out
						.println("\t[freemarker] Warning: variable not defined "
								+ getSource());
			}
		} catch (Exception exc) {
			val = getSource();
			System.out.println("\t[freemarker] Warning: variable not defined "
					+ getSource());
		}
		env.getOut().write(val);
	}

_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________


koevet wrote:
> 
> Hello, I have just started using Freemarker.
> 
> I have a basic problem. How do I set the template to handle null values of
> an int field of a pojo as String and display no values? 
> Currently my template looks like:
> 
> Event: "${event.eventSource!""}","${event.eventType!""}
> 
> eventType is a int field of a pojo. If the field is null, Freemarker
> displays 0 (default for int). I would like to change the behavior to
> display an empty String. And no, I can't change the type to Integer.
> 
> Thanks
> Luciano
> 

-- 
View this message in context: http://www.nabble.com/Handling-null-values-tp18997775p25305593.html
Sent from the freemarker-user mailing list archive at Nabble.com.


------------------------------------------------------------------------------
Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day 
trial. Simplify your report design, integration and deployment - and focus on 
what you do best, core application coding. Discover what's new with 
Crystal Reports now.  http://p.sf.net/sfu/bobj-july
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.