package org.qfox.jestful.template.taglib;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;

/**
 * Created by yangchangpei on 17/4/19.
 */
public class Fragment extends BodyTagSupport {
    private static final long serialVersionUID = -4410234723867630259L;

    private String name;

    public Fragment() {
    }

    public Fragment(String name) {
        this.name = name;
    }

    @Override
    public int doStartTag() throws JspException {
        try {
            // 赋值
            if (getParent() instanceof Layout) {
                // 缓存body
                return EVAL_BODY_BUFFERED;
            }
            // 渲染
            else {
                ServletRequest request = pageContext.getRequest();
                String content = (String) request.getAttribute(name);
                // 如果有值则不需要渲染body了
                if (content != null) {
                    pageContext.getOut().print(content);
                    return SKIP_BODY;
                }
                // 否则还是要渲染body
                else {
                    return EVAL_BODY_BUFFERED;
                }
            }
        } catch (IOException e) {
            throw new JspException(e);
        }
    }

    @Override
    public int doEndTag() throws JspException {
        try {
            // 赋值
            if (getParent() instanceof Layout) {
                if (bodyContent != null) {
                    String content = bodyContent.getString();
                    pageContext.getRequest().setAttribute(name, content);
                }
            }
            // 渲染
            else {
                if (bodyContent != null) {
                    String content = bodyContent.getString();
                    pageContext.getOut().print(content);
                }
            }
            // 继续
            return EVAL_PAGE;
        } catch (IOException e) {
            throw new JspException(e);
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@@ -160,16 +160,53 @@
 upport;%0A
+import javax.servlet.jsp.tagext.Tag;%0A
 import j
@@ -225,16 +225,16 @@
 eption;%0A
-
 %0A/**%0A * 
@@ -510,32 +510,280 @@
  = name;%0A    %7D%0A%0A
+    protected boolean insideOfLayout() %7B%0A        Tag parent = getParent();%0A        while (parent != null) %7B%0A            if (parent instanceof Layout) return true;%0A            else parent = parent.getParent();%0A        %7D%0A        return false;%0A    %7D%0A%0A
     @Override%0A  
@@ -882,37 +882,24 @@
 if (
-getParent() instanceof 
+insideOf
 Layout
+()
 ) %7B%0A
@@ -1679,37 +1679,24 @@
 if (
-getParent() instanceof 
+insideOf
 Layout
+()
 ) %7B%0A

Add jestful-template Module