This is an example of a block handler function. This one handles the loop tag.
774779
function ClosedBlock_Handle_Loop(&$res)
    {
        if ($res['ArgumentCount'] > 1) {
            throw new SSTemplateParseException('Either no or too many arguments in control block. Must be one ' .
                'argument only.', $this);
        }

        //loop without arguments loops on the current scope
        if ($res['ArgumentCount'] == 0) {
            $on = '$scope->obj(\'Up\', null)->obj(\'Foo\', null)';
        } else {    //loop in the normal way
            $arg = $res['Arguments'][0];
            if ($arg['ArgumentMode'] == 'string') {
                throw new SSTemplateParseException('Control block cant take string as argument.', $this);
            }
            $on = str_replace(
                '$$FINAL',
                'obj',
                ($arg['ArgumentMode'] == 'default') ? $arg['lookup_php'] : $arg['php']
            );
        }

        return
            $on . '; $scope->pushScope(); while (($key = $scope->next()) !== false) {' . PHP_EOL .
                $res['Template']['php'] . PHP_EOL .
            '}; $scope->popScope(); ';
    }
930929
function (blockList) {
        this.errors = [];
        this.tree = new Node("file", null);
        this.tree.content = [];

        this._advance(blockList, 0, this.tree.content);

        this._postProcessTree();
    }
57210
function() {
    Dom.hide(this.el);

    this.errorHandler = new ErrorHandler(this.outer, this.mediator, this.options.errorsContainer);
    this.store = new EditorStore(this.el.value, this.mediator);

    this.blockManager = new BlockManager(this);
    this.blockAddition = BlockAddition.create(this);
    this.BlockAdditionTop = BlockAdditionTop.create(this);
    this.blockControls = BlockControls.create(this);
    this.blockPositionerSelect = new BlockPositionerSelect(this.mediator);
    this.selectionHandler = new SelectionHandler(this.outer, this.mediator, this);
    this.formatBar = new FormatBar(this.options.formatBar, this.mediator, this);

    this.mediator.on('block:changePosition', this.changeBlockPosition);
    this.mediator.on('block:limitReached', this.blockLimitReached);

    // Apply specific classes when block order is updated
    this.mediator.on('block:rerender', this.blockOrderUpdated);
    this.mediator.on('block:create', this.blockOrderUpdated);
    this.mediator.on('block:remove', this.blockOrderUpdated);
    this.mediator.on('block:replace', this.blockOrderUpdated);
    this.mediator.on("block:countUpdate", this.onBlockCountChange);
    this.mediator.on("block-positioner-select:render", this.renderBlockPositionerSelect);

    this.dataStore = "Please use store.retrieve();";

    this._setEvents();

    // External event listeners
    window.addEventListener('click', this.hideAllTheThings);
    document.body.addEventListener('keydown', this.disableBackButton);

    this.createBlocks();
    this.wrapper.classList.add('st-ready');

    if(!_.isUndefined(this.onEditorRender)) {
      this.onEditorRender();
    }
  }
1083131
def parse_Element(self, node):
        
        name = node.tagName
        ignores = self.ignores
        if name in ignores:
            return
        attr = "do_%s" % name
        if hasattr(self, attr):
            handlerMethod = getattr(self, attr)
            handlerMethod(node)
        else:
            self.generic_parse(node)
1081701
function processBlocks(textString, options, data) {

	var replacer = function replacer(match, $1, $2, $3, $4, $5, $6, offset, input) {
		var out = '',
			dataValue,
			type = String($2),
			key = String($3 || '').trim(),
			blockText = String($5),
			nestedBlocks;

		dataValue = _extract(key, data);

		if (options && typeof options === 'object' && options.strictKeys) {
			if(Number.isNaN(dataValue)) {
				return match;
			}
		}

		nestedBlocks = blockText.match(pattern);
		if (nestedBlocks) {
			blockText = blockText.replace(pattern, function(match, $1, $2, $3, $4, $5, $6, offset, input) {
				var index = match.indexOf($5);
				var length = $5.length;
				var body = $5.replace(/(?:\\*)\[(.+?)(?:\\*)\]/g, "\\[$1]");
				return match.substr(0, index) + body + match.substr(index + length);
			});
		}

		var obj = {}, proto = {}, KEY;
		if (typeof dataValue === 'object' && type === '#') {
			for(KEY in dataValue) {
				obj = {}, proto = {};
				proto.KEY = proto.INDEX = KEY;
				obj[KEY] = proto.VALUE = dataValue[KEY];
				obj.__proto__ = proto;
				if (typeof dataValue[KEY] === 'object' && !isNaN(parseInt(KEY))) {
					obj = dataValue[KEY];
					obj.__proto__ = proto;
				}
				out += renderData(blockText, options, obj, Boolean(options.prefix));
			}
			if (nestedBlocks) {
				out = processBlocks(out, options, data);
			}
		} else if (dataValue && (type === '~' || type === '#')) {
			// block logical truthy
			proto.KEY = proto.INDEX = key;
			proto.VALUE = Boolean(dataValue);
			obj = data;
			obj.__proto__ = proto;

			out += renderData(blockText, options, obj, Boolean(options.prefix));
			if (nestedBlocks) {
				out = processBlocks(out, options, data);
			}
		} else if (!dataValue && (type === '^' || type === '!')) {
			// block logical falsy
			proto.KEY = proto.INDEX = key;
			proto.VALUE = Boolean(dataValue);
			obj = data;
			obj.__proto__ = proto;

			out += renderData(blockText, options, obj, Boolean(options.prefix));
			if (nestedBlocks) {
				out = processBlocks(out, options, data);
			}
		}
		return out;
	};

	var pattern = new RegExp('(\\[\\s*(~|\\^|\\!|#)([^\\r\\n]+)\\s*\\])([\\s]?)([\\s\\S]*?)(\\[\\s*\\/\\3\\s*\\]\\4?)', 'mg');

	if(typeof data === 'object' && data !== null) {
		if (options && typeof options === 'object' && options.prefix) {
			pattern = new RegExp('(\\[\\s*(~|\\^|\\!|#)'+rxquote(String(options.prefix))+'[\\.\\-\\_]([^\\r\\n]+)\\s*\\])(\\s?)([\\s\\S]*?)(\\[\\s*\\/'+rxquote(String(options.prefix))+'[\\.\\-\\_]\\3\\s*\\]\\4?)', 'mg');
		}
		textString = textString.replace(pattern, replacer);
	}

	return textString;
}
415695
def _handle_for(self, node, scope, ctxt, stream):
        
        self._dlog("handling for")
        if node.init is not None:
            # perform the init
            self._handle_node(node.init, scope, ctxt, stream)

        while node.cond is None or self._handle_node(node.cond, scope, ctxt, stream):
            if node.stmt is not None:
                try:
                    # do the for body
                    self._handle_node(node.stmt, scope, ctxt, stream)
                except errors.InterpBreak as e:
                    break
                
                # we still need to interpret the "next" statement,
                # so just pass
                except errors.InterpContinue as e:
                    pass

            if node.next is not None:
                # do the next statement
                self._handle_node(node.next, scope, ctxt, stream)
1238295
function handleBlock(startArr, startOffsetM, startOffsetNextM, destArr, destOffsetM, destOffsetNextM, undefined){

  // slice out the block we need
  var startArrTemp = startArr.slice(startOffsetM, startOffsetNextM || undefined)
    ,  destArrTemp =  destArr.slice( destOffsetM,  destOffsetNextM || undefined)

  var i = 0
    , posStart = {pos:[0,0], start:[0,0]}
    , posDest  = {pos:[0,0], start:[0,0]}

  do{

    // convert shorthand types to long form
    startArrTemp[i] = simplyfy.call(posStart, startArrTemp[i])
     destArrTemp[i] = simplyfy.call(posDest ,  destArrTemp[i])

    // check if both shape types match
    // 2 elliptical arc curve commands ('A'), are considered different if the
    // flags (large-arc-flag, sweep-flag) don't match
    if(startArrTemp[i][0] != destArrTemp[i][0] || startArrTemp[i][0] == 'M' ||
        (startArrTemp[i][0] == 'A' &&
          (startArrTemp[i][4] != destArrTemp[i][4] || startArrTemp[i][5] != destArrTemp[i][5])
        )
      ) {

      // if not, convert shapes to beziere
      Array.prototype.splice.apply(startArrTemp, [i, 1].concat(toBeziere.call(posStart, startArrTemp[i])))
       Array.prototype.splice.apply(destArrTemp, [i, 1].concat(toBeziere.call(posDest, destArrTemp[i])))

    } else {

      // only update positions otherwise
      startArrTemp[i] = setPosAndReflection.call(posStart, startArrTemp[i])
       destArrTemp[i] = setPosAndReflection.call(posDest ,  destArrTemp[i])

    }

    // we are at the end at both arrays. stop here
    if(++i == startArrTemp.length && i == destArrTemp.length) break

    // destArray is longer. Add one element
    if(i == startArrTemp.length){
      startArrTemp.push([
        'C',
        posStart.pos[0],
        posStart.pos[1],
        posStart.pos[0],
        posStart.pos[1],
        posStart.pos[0],
        posStart.pos[1],
      ])
    }

    // startArr is longer. Add one element
    if(i == destArrTemp.length){
      destArrTemp.push([
        'C',
        posDest.pos[0],
        posDest.pos[1],
        posDest.pos[0],
        posDest.pos[1],
        posDest.pos[0],
        posDest.pos[1]
      ])
    }


  }while(true)

  // return the updated block
  return {start:startArrTemp, dest:destArrTemp}
}
705409
function loopThroughHandlers(lastFuture, n) {
            if(n < routes.length) {
                var route = routes[n].route
                var handler = route[handlerProperty]

                if(direction === -1) {
                    var originalIndexFromCurrentRoutes = currentRoutes.length - n - 1
                    var distance = routes.length - n        // divergenceDistance
                } else {
                    var originalIndexFromCurrentRoutes = routeVergenceIndex+n
                    var distance = undefined                // no more leafDistance: routes.length - n - 1    // leafDistance
                }

                return lastFuture.then(function() {
                    if(handler !== undefined) {
                        if(originalIndexFromCurrentRoutes > 0) {
                            var parentRoute = currentRoutes[originalIndexFromCurrentRoutes-1]
                            var lastValue = parentRoute.route.lastValue
                        }

                        var nextFuture = handler.call(route, lastValue, distance)
                        if(nextFuture !== undefined) {
                            nextFuture.then(function(value) {
                                route.lastValue = value
                            }) // no done because nextFuture's errors are handled elsewhere
                        }
                    }

                    if(nextFuture === undefined) {
                        nextFuture = Future(undefined)
                    }

                    return loopThroughHandlers(nextFuture, n+1)

                }).catch(function(e){
                    return handleError(currentRoutes, originalIndexFromCurrentRoutes, type, e, []).then(function() {
                        if(direction === 1) {
                            return Future(n + routeVergenceIndex)
                        } else { // -1 exit handlers
                            return loopThroughHandlers(Future(undefined), n+1)  // continue executing the parent exit handlers
                        }
                    })
                })
            } else {
                return lastFuture.then(function() {
                    return Future(n + routeVergenceIndex)
                }).catch(function(e) {
                    throw e // propagate the error not the value
                })
            }
        }
1099711
protected DCTree blockTag() {
        int p = bp;
        try {
            nextChar();
            if (isIdentifierStart(ch)) {
                Name name = readTagName();
                TagParser tp = tagParsers.get(name);
                if (tp == null) {
                    List<DCTree> content = blockContent();
                    return m.at(p).UnknownBlockTag(name, content);
                } else {
                    switch (tp.getKind()) {
                        case BLOCK:
                            return tp.parse(p);
                        case INLINE:
                            return erroneous("dc.bad.inline.tag", p);
                    }
                }
            }
            blockContent();

            return erroneous("dc.no.tag.name", p);
        } catch (ParseException e) {
            blockContent();
            return erroneous(e.getMessage(), p);
        }
    }
519754
function(e) {
    var legal = false;
    // Is the block nested in a loop?
    var block = this;
    do {
      if (this.LOOP_TYPES.indexOf(block.type) != -1) {
        legal = true;
        break;
      }
      block = block.getSurroundParent();
    } while (block);
    if (legal) {
      this.setWarningText(null);
    } else {
      this.setWarningText(Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING);
    }
  }
543669
function exampleHandlers(customHandlers) {
    return (customHandlers || []).concat([
      {
        pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*===?\s*(.*)$/,
        template: 'equality',
        data: function(match) {
          return {
            left: match[1],
            right: match[2]
          };
        }
      },
      {
        pattern: /^(\w[\w\.\(\)\[\]'"]*)\s*!==?\s*(.*)$/,
        template: 'inequality',
        data: function(match) {
          return {
            left: match[1],
            right: match[2]
          };
        }
      },
      {
        pattern: /^instanceof (.*)$/,
        template: 'instanceof',
        data: function(match) {
          return { type: match[1] };
        }
      },
      {
        pattern: /^NaN$/,
        template: 'nan'
      },
      {
        pattern: /^throws$/,
        template: 'throws'
      },
      {
        pattern: /^calls\s+(\w+)\s+(\d+)(?:\s+times?)?$/,
        template: 'calls',
        data: function(match) {
          return {
            callback: match[1],
            count: getCount(match[2])
          };
        }
      },
      {
        pattern: /^calls\s+(\w+)\s+(\d+)\s+times? asynchronously$/,
        template: 'calls_async',
        data: function(match) {
          return {
            callback: match[1],
            count: getCount(match[2])
          };
        }
      },
      {
        pattern: /^=~\s+\/(.*)\/$/,
        template: 'string_proximity',
        data: function(match) {
          return { pattern: match[1] };
        }
      },
      {
        pattern: /^=~\s+\[(.*),?\s*\.\.\.\s*\]$/,
        template: 'array_inclusion',
        data: function(match) {
          return { elements: match[1] };
        }
      },
      {
        pattern: /^one of (.*)$/,
        template: 'array_membership',
        data: function(match) {
          return { values: match[1] };
        }
      },
      {
        pattern: /^=~\s+\[(.*)\]$/,
        template: 'array_proximity',
        data: function(match) {
          return { elements: match[1] };
        }
      },
      {
        pattern: /^\[(.*),?\s*\.\.\.\s*\]$/,
        template: 'array_head',
        data: function(match) {
          return { head: match[1] };
        }
      },
      {
        pattern: /^\[\s*\.\.\.,?\s*(.*)\]$/,
        template: 'array_tail',
        data: function(match) {
          return { tail: match[1] };
        }
      },
      {
        pattern: /\{([\s\S]*),?[\s\n]*\.\.\.[\s\n]*\}/,
        template: 'object_proximity',
        data: function(match) {
          return { properties: match[1] };
        }
      }
    ]);
  }
300712
def _process_loop_helper(self, node, **kwargs):
        

        if node.attr == LOOP_HELPER_INDEX:
            self.output.write('(arguments[1] + 1)')
        elif node.attr == LOOP_HELPER_INDEX_0:
            self.output.write('arguments[1]')
        elif node.attr == LOOP_HELPER_FIRST:
            self.output.write('(arguments[1] == 0)')
        elif node.attr == LOOP_HELPER_LAST:
            self.output.write('(arguments[1] == arguments[2].length - 1)')
        elif node.attr == LOOP_HELPER_LENGTH:
            self.output.write('arguments[2].length')
101876
function(loop){
    var test = loop.test;
    var whileBlock = this.visit(loop.block, loop);
    var w = t.whileStatement(
      loop.astTest || this.parseExpr(test),
      t.blockStatement(whileBlock)
    );
    return [w];
  }
659421
function handleTagToText() {
    if (!$this->keepHTML) {
      if (!$this->parser->isStartTag && $this->parser->isBlockElement) {
        $this->setLineBreaks(2);
      }
    } else {
      # dont convert to markdown inside this tag
      /** TODO: markdown extra **/
      if (!$this->parser->isEmptyTag) {
        if ($this->parser->isStartTag) {
          if (!$this->skipConversion) {
            $this->skipConversion = $this->parser->tagName.'::'.implode('/', $this->parser->openTags);
          }
        } else {
          if ($this->skipConversion == $this->parser->tagName.'::'.implode('/', $this->parser->openTags)) {
            $this->skipConversion = false;
          }
        }
      }

      if ($this->parser->isBlockElement) {
        if ($this->parser->isStartTag) {
          if (in_array($this->parent(), array('ins', 'del'))) {
            # looks like ins or del are block elements now
            $this->out("\n", true);
            $this->indent('  ');
          }
          if ($this->parser->tagName != 'pre') {
            $this->out($this->parser->node."\n".$this->indent);
            if (!$this->parser->isEmptyTag) {
              $this->indent('  ');
            } else {
              $this->setLineBreaks(1);
            }
            $this->parser->html = ltrim($this->parser->html);
          } else {
            # don't indent inside <pre> tags
            $this->out($this->parser->node);
            static $indent;
            $indent =  $this->indent;
            $this->indent = '';
          }
        } else {
          if (!$this->parser->keepWhitespace) {
            $this->output = rtrim($this->output);
          }
          if ($this->parser->tagName != 'pre') {
            $this->indent('  ');
            $this->out("\n".$this->indent.$this->parser->node);
          } else {
            # reset indentation
            $this->out($this->parser->node);
            static $indent;
            $this->indent = $indent;
          }

          if (in_array($this->parent(), array('ins', 'del'))) {
            # ins or del was block element
            $this->out("\n");
            $this->indent('  ');
          }
          if ($this->parser->tagName == 'li') {
            $this->setLineBreaks(1);
          } else {
            $this->setLineBreaks(2);
          }
        }
      } else {
        $this->out($this->parser->node);
      }
      if (in_array($this->parser->tagName, array('code', 'pre'))) {
        if ($this->parser->isStartTag) {
          $this->buffer();
        } else {
          # add stuff so cleanup just reverses this
          $this->out(str_replace('&lt;', '&amp;lt;', str_replace('&gt;', '&amp;gt;', $this->unbuffer())));
        }
      }
    }
  }
644448
function process( $tpl, &$textElements, $functionName, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace )
    {
        if ( count( $functionParameters ) == 0 || !count( $functionParameters['condition'] ) )
        {
            eZDebug::writeError( "Not enough arguments passed to 'if' function." );
            return;
        }

        $ifValue = $tpl->elementValue( $functionParameters['condition'], $rootNamespace, $currentNamespace, $functionPlacement );

        $show        = $ifValue; // whether to show the child being currently processing
        $showWasTrue = $show;    // true if $show has been assigned 'true' value at least once in the current {if}...{/if} block.
        $foundElse   = false;    // true if 'else' has been met once in the current {if}...{/if} block.

        if ( !is_array( $functionChildren ) )
        {
            return;
        }
        foreach ( $functionChildren as $key => $child )
        {
            $childType = $child[0];

            // parse 'elseif', 'else' functions
            if ( $childType == eZTemplate::NODE_FUNCTION )
            {
                $childFunctionName      =& $child[2];
                $childFunctionArgs      =& $child[3];
                $childFunctionPlacement =& $child[4];

                if ( $childFunctionName == 'else' )
                {
                    if ( $foundElse  )
                    {
                        eZDebug::writeError( "Duplicated 'else'" );
                        $show = false;
                        continue;
                    }

                    $show = !$showWasTrue;
                    $foundElse = true;
                    continue;
                }
                elseif ( $childFunctionName == 'elseif' )
                {
                    if ( $foundElse  )
                    {
                        eZDebug::writeError( "There should be no more 'elseif' after 'else'" );
                        $show = false;
                        continue;
                    }

                    if ( !isset( $childFunctionArgs['condition'] ) || !count( $childFunctionArgs['condition'] ) ) // no arguments passes to 'elseif' (should not happen)
                        $elseifValue = false;
                    else
                        $elseifValue = $tpl->elementValue( $childFunctionArgs['condition'], $rootNamespace, $currentNamespace, $functionPlacement );

                    if ( !$showWasTrue && $elseifValue )
                        $show = $showWasTrue = true;
                    else
                        $show = false;
                    continue;
                }
                elseif ( $childFunctionName == 'break' )
                {
                    if ( !$show )
                            continue;
                    return array( 'breakFunctionFound' => 1 );
                }
                elseif ( $childFunctionName == 'continue' )
                {
                    if ( !$show )
                            continue;
                    return array( 'continueFunctionFound' => 1 );
                }
                elseif ( $childFunctionName == 'skip' )
                {
                    if ( !$show )
                            continue;
                    return array( 'skipFunctionFound' => 1 );
                }
            }

            if ( $show )
            {
                $rslt = $tpl->processNode( $child, $textElements, $rootNamespace, $currentNamespace );

                // handle 'break', 'continue' and 'skip'
                if ( is_array( $rslt ) && ( array_key_exists( 'breakFunctionFound', $rslt ) ||
                                            array_key_exists( 'continueFunctionFound', $rslt )  ||
                                            array_key_exists( 'skipFunctionFound', $rslt ) ) )
                {
                    return $rslt;
                }
            }
        }
    }
299402
function process( $tpl, &$textElements, $functionName, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace )
    {
        if ( count( $functionParameters ) == 0 )
        {
            eZDebug::writeError( "Not enough arguments passed to 'while' function." );
            return;
        }

        $loop = new eZTemplateLoop( eZTemplateWhileFunction::FUNCTION_NAME,
                                    $functionParameters, $functionChildren, $functionPlacement,
                                    $tpl, $textElements, $rootNamespace, $currentNamespace );

        if ( !$loop->initialized() )
            return;

        while ( $tpl->elementValue( $functionParameters['condition'], $rootNamespace, $currentNamespace, $functionPlacement ) )
        {
            $loop->setSequenceVar(); // set sequence variable (if specified)
            $loop->processDelimiter();
            $loop->resetIteration();

            if ( $loop->processChildren() )
                break;

            $loop->incrementSequence();
        }

        $loop->cleanup();
    }
856273
static void capturePageEvent(String eventName, final EventHandler handler) {
    HtmlPlatform.captureEvent(eventName, new EventHandler() {
      @Override
      public void handleEvent(NativeEvent evt) {
        handler.handleEvent(evt);
      }
    });
  }