Skip blocks of a content item that are children of a template block and do not match the content id.
The reason for this is that template blocks could have children from different content items

{@inheritdoc}
347167
public function shouldSkipClass(ClassMetadata $metadata, Context $context)
    {
        $obj = null;
        // Get the last item of the visiting set
        foreach ($context->getVisitingSet() as $item) {
            $obj = $item;
        }

        if ($obj && $obj instanceof Block && $obj->getParent() && $obj->getParent()->getTemplate() && $obj->getContent() && $obj->getContentId() != $this->content->getId()) {
            return true;
        }

        return false;
    }
975567
function replaceBlocks(content, blocks) {
    var newContent = content.replace(/\{\{\-\%([\s\S]+?)\%\-\}\}/g, function(match, key) {
        var replacedWith = match;

        var block = blocks.get(key);
        if (block) {
            replacedWith = replaceBlocks(block.get('body'), blocks);
        }

        return replacedWith;
    });

    return newContent;
}
749098
public function stopParent()
    {
        if (!empty($this->currentBlockName)) {
            throw new InvalidParamException("Unclosed startBlock detected in '{$this->processingViewFile}'");
        }
        if (empty($this->_extendingParent[$this->processingViewFile])) {
            throw new InvalidParamException("stopParent unexpected here without startParent in '{$this->processingViewFile}'");
        }
        $this->_extendingParent[$this->processingViewFile] = false;

        $lost = ob_get_clean(); // lost all non-block info between startParent...stopParent
        
        // render parent view with blocks inclusions
        $parentFile = $this->findParentViewFile($this->processingViewFile);
        if ($parentFile) {
            $this->_currentViewFile[$this->viewFile] = $parentFile;

            $parentDataFile = $this->viewFile;
            $params = empty($this->_viewsParams[$parentDataFile]) ? [] : $this->_viewsParams[$parentDataFile];
            if (!empty($this->_addParentData[$parentDataFile])) {
                $addParentData = $this->_addParentData[$parentDataFile];
                $params = ArrayHelper::merge($params, $addParentData);
            }
            $result = $this->renderPhpFile($parentFile, $params);
            $n = $this->hasParentBlock($result);
            while ($n--) {
                $result = $this->replaceParentBlock($result);
            }
            if ($this->hasParentBlock($result)) {
                throw new InvalidParamException("Unprocessed nested parentBlock found in '{$this->processingViewFile}'");
            }            
            echo $result;
        }
    }
895013
@Override
  public Iterable<BlockTemplateMatch> match(JCTree tree, Context context) {
    // TODO(lowasser): consider nonconsecutive matches?
    if (tree instanceof JCBlock) {
      JCBlock block = (JCBlock) tree;
      ImmutableList<JCStatement> targetStatements = ImmutableList.copyOf(block.getStatements());
      return matchesStartingAnywhere(block, 0, targetStatements, context)
          .first()
          .or(List.<BlockTemplateMatch>nil());
    }
    return ImmutableList.of();
  }
27762
public function recursiveTidy($children)
    {

        foreach ($children as $page) {
            $write = false;

            // This is so something (events for example) can be purged.

            if ($this->purge && is_a($page, $this->purge, true)) {
                $page->delete();
                $this->purged++;
                continue;
            }

            // The most common issue is that the site ID doesn't match.

            if ($page->SiteID != $this->siteID) {

                // Update it to match.

                $page->SiteID = $this->siteID;
                $write        = true;
            }

            // The next issue is that duplicated URL segments have numbers appended (`URL-segment-2` for example).

            if (preg_match('%-[0-9]$%', $page->URLSegment)) {

                // When a page title ends with a number, the URL should match this.

                $last = substr($page->Title, -1);
                if (is_numeric($last)) {

                    // Determine whether this actually needs fixing.

                    if ($last !== substr($page->URLSegment, -1)) {

                        // Update it to match.

                        $page->URLSegment = $page->Title;
                        $write            = true;
                    }
                }

                // The number appended shouldn't exist.
                else {

                    // Determine whether this is considered unique (otherwise it can't be updated).

                    $to = substr($page->URLSegment, 0, -2);
                    if (!SiteTree::get()->filter(array(
                            'ParentID' => $page->ParentID,
                            'URLSegment' => $to
                        ))->exists()) {

                        // This isn't unique, so update it.

                        $page->URLSegment = $to;
                        $write            = true;
                    }
                }
            }

            // Determine whether this page needs a write.

            if ($write) {
                $page->write();
                $this->count++;
            }

            // Where necessary, continue further down.

            $this->recursiveTidy($page->AllChildren());
        }
    }
886754
public function endblock()
    {
        $name = $this->getBlockQueue()->pop();

        // If this block name not exists on parent level, we just echo inner content.
        if (!empty($this->block[$name])) {
            ob_get_clean();

            echo $this->block[$name];

            return;
        }

        // Get the layout contents.
        echo $this->block[$name] = ob_get_clean();
    }
505607
public function stopBlock($name = null)
    {
        if (empty($this->currentBlockName)) {
            throw new InvalidParamException(
                "Unexpected stopBlock in '{$this->processingViewFile}'"
            );
        }
        if (!empty($name) && $this->currentBlockName != $name) {
            throw new InvalidParamException(
                "Expected current closed block name '{$this->currentBlockName}' instead of '{$name}'"
              . " in '{$this->processingViewFile}'"
            );
        }
        $name = $this->currentBlockName;

        $fullBlockName = $this->getCurrentBlockFullName();

        array_pop(static::$_blocksStack);

        $content = ob_get_clean();

        // save every block of every view-file in inherit chain (not only for last) - it will need for render parentBlock
        if (!$this->viewBlocks($this->processingViewFile)->exists($fullBlockName)) {
            $this->viewBlocks($this->processingViewFile)->add($fullBlockName, $content);
        }

        $savedContent = $this->findProperBlock($fullBlockName, $this->processingViewFile);
        if ($savedContent !== false) {
            $content = $savedContent; // rewrite
        }
        if ($savedContent !== false && empty($this->_extendingParent[$this->processingViewFile])) {
            // such block already saved - replace block in parent view-template by saved content
            $n = $this->hasParentBlock($savedContent);
            while ($n--) {
                $savedContent = $this->replaceParentBlock($savedContent);
            }
            echo $savedContent;
        } else {
            echo $content; // always echo - to catch by outer block
        }
    }
1180355
public function edit($content)
    {
        if (!array_key_exists('selectOptions', $this->_editViewData)) {
            $this->_editViewData['selectOptions'] = [];
            $selectOptions = BlockSelectOption::where('block_id', '=', $this->_block->id)->get();
            foreach ($selectOptions as $selectOption) {
                $this->_editViewData['selectOptions'][$selectOption->value] = $selectOption->option;
            }
            if (preg_match('/^#[a-f0-9]{6}$/i', key($selectOptions))) {
                $this->_editViewData['class'] = 'select_colour';
            }
        }
        return parent::edit($content);
    }
360138
function removeNestedBlocks (ast) {
  var tagged;
  while((tagged = findNestedBlocks(ast)).length) {
    fast.forEach(tagged, function (item) {
      var node = item[0],
          parent = item[1],
          index = parent.body.indexOf(node);
      fast.apply(Array.prototype.splice, parent.body, fast.concat([index, 1], node.body));
    });
  }
  return ast;
}
1072909
public function getValidBlockItemsAsContentInfo(Block $block)
    {
        $contentInfoObjects = array();
        foreach ($this->getValidBlockItems($block) as $item) {
            try {
                $contentInfoObjects[] = $this->contentService->loadContentInfo($item->contentId);
            } catch (UnauthorizedException $e) {
                // If unauthorized, disregard block as "valid" and continue loading other blocks.
            }
        }

        return $contentInfoObjects;
    }
753020
@Nullable
  private static Node getOnlyInterestingChild(Node block) {
    if (!block.isBlock()) {
      return null;
    }
    if (block.hasOneChild()) {
      return block.getOnlyChild();
    }

    Node ret = null;
    for (Node child : block.children()) {
      if (child.isSyntheticBlock() && !child.hasChildren()) {
        // Uninteresting child.
      } else if (ret != null) {
        // Found more than one interesting child.
        return null;
      } else {
        ret = child;
      }
    }
    return ret;
  }
1272192
function hasObjectAttributeContent( $contentObjectAttribute )
    {
        $page = $contentObjectAttribute->content();
        $zones = $page->attribute( 'zones' );
        if ( !is_array( $zones ) )
            return false;

        foreach ( $zones as $zone )
        {
            if ( $zone->getBlockCount() > 0 )
                return true;
        }

        return false;
    }
504171
public function replaceBlock(BlockElement $block, array $children = null)
    {
        if ($parent = $block->getParent()) {
            foreach (array_reverse($children ?: $block->getChildren()) as $child) {
                $parent->insertAfter($block, $child);
            }
            $previous = $block->getPreviousSibling();
            if ($previous instanceof TextElement) {
                $previous->setEnd(true);
            }
            $block->remove();
        }
    }
35018
function DOMChildrenWalker(el) {
    this.raw = [];
    this.index = 0;
    this.target = el;

    var child = el.firstChild;
    var next;
    while (child) {
        next = child.nextSibling;

        switch (child.nodeType) {
            case 3:
                if (/^\s*$/.test(child.data || child.textContent)) {
                    removeEl(child);
                }
                else {
                    this.raw.push(child);
                }
                break;

            case 1:
            case 8:
                this.raw.push(child);
        }

        child = next;
    }

    this.current = this.raw[this.index];
    this.next = this.raw[this.index + 1];
}
1187443
public function filterContent() {
		$removals = $this->parseItemsToRemove();

		// Bail out early if nothing to do
		if ( \array_reduce( $removals,
			function ( $carry, $item ) {
				return $carry && !$item;
			},
			true
		) ) {
			return [];
		}

		$doc = $this->getDoc();

		// Remove tags

		// You can't remove DOMNodes from a DOMNodeList as you're iterating
		// over them in a foreach loop. It will seemingly leave the internal
		// iterator on the foreach out of wack and results will be quite
		// strange. Though, making a queue of items to remove seems to work.
		$domElemsToRemove = [];
		foreach ( $removals['TAG'] as $tagToRemove ) {
			$tagToRemoveNodes = $doc->getElementsByTagName( $tagToRemove );
			foreach ( $tagToRemoveNodes as $tagToRemoveNode ) {
				if ( $tagToRemoveNode ) {
					$domElemsToRemove[] = $tagToRemoveNode;
				}
			}
		}
		$removed = $this->removeElements( $domElemsToRemove );

		// Elements with named IDs
		$domElemsToRemove = [];
		foreach ( $removals['ID'] as $itemToRemove ) {
			$itemToRemoveNode = $doc->getElementById( $itemToRemove );
			if ( $itemToRemoveNode ) {
				$domElemsToRemove[] = $itemToRemoveNode;
			}
		}
		$removed = array_merge( $removed, $this->removeElements( $domElemsToRemove ) );

		// CSS Classes
		$domElemsToRemove = [];
		$xpath = new \DOMXPath( $doc );
		foreach ( $removals['CLASS'] as $classToRemove ) {
			$elements = $xpath->query( '//*[contains(@class, "' . $classToRemove . '")]' );

			/** @var $element \DOMElement */
			foreach ( $elements as $element ) {
				$classes = $element->getAttribute( 'class' );
				if ( \preg_match( "/\b$classToRemove\b/", $classes ) && $element->parentNode ) {
					$domElemsToRemove[] = $element;
				}
			}
		}
		$removed = \array_merge( $removed, $this->removeElements( $domElemsToRemove ) );

		// Tags with CSS Classes
		foreach ( $removals['TAG_CLASS'] as $classToRemove ) {
			$parts = explode( '.', $classToRemove );

			$elements = $xpath->query(
				'//' . $parts[0] . '[@class="' . $parts[1] . '"]'
			);
			$removed = array_merge( $removed, $this->removeElements( $elements ) );
		}

		return $removed;
	}
587190
def remove!(&block)
      
      # @note #groups and #files is used because it adds the very precious
      #   supergroup to each of the child items.
      
      groups.each {|group| group.remove!(&block) }
      files.each {|file| file.remove!(&block) }
      yield self if block_given?
      
      child_identifier = identifier
      supergroup.instance_eval { remove_child_object(child_identifier) }
      @registry.remove_object identifier
    end
19547
public function resetContent(PageInterface $page, LayoutBlock $layoutBlock, \JMS\Serializer\SerializerInterface $serializer)
    {
	    if ($contentObject = $layoutBlock->getSnapshotContent()) {
		    $contentObject = $serializer->deserialize($contentObject, $layoutBlock->getClassType(), 'json');



		    try {
			    $contentObject = $this->_em->merge($contentObject);
			    $reflection = new \ReflectionClass($contentObject);
			    foreach ($reflection->getProperties() as $property) {
				    $method = sprintf('get%s', ucfirst($property->getName()));
				    if ($reflection->hasMethod($method) && $var = $contentObject->{$method}()) {
					    if ($var instanceof ArrayCollection) {
						    foreach ($var as $key =>  $v) {
							    $v = $this->_em->merge($v);

							    $var->set($key, $v);
						    }
						    $method = sprintf('set%s', ucfirst($property->getName()));
						    $contentObject->{$method}($var);
					    }

					    if(is_object($var) && $this->_em->getMetadataFactory()->hasMetadataFor(get_class($var))){
						    $var = $this->_em->merge($var);

						    $method = sprintf('set%s', ucfirst($property->getName()));
						    $contentObject->{$method}($var);
					    }
				    }
			    }

			    $this->_em->persist($contentObject);
			    $this->_em->flush($contentObject);

		    } catch (EntityNotFoundException $e) {
			    $classType = $layoutBlock->getClassType();
			    $newContentObject = clone $contentObject;
			    $reflection = new \ReflectionClass($contentObject);
			    foreach ($reflection->getProperties() as $property) {
				    $method = sprintf('get%s', ucfirst($property->getName()));
				    if ($reflection->hasMethod($method) && $var = $contentObject->{$method}()) {
					    if ($var instanceof ArrayCollection) {
						    foreach ($var as $key =>  $v) {
							    $v = $this->_em->merge($v);

							    $var->set($key, $v);
						    }
						    $method = sprintf('set%s', ucfirst($property->getName()));
						    $newContentObject->{$method}($var);
					    }

					    if(is_object($var) && $this->_em->getMetadataFactory()->hasMetadataFor(get_class($var))){
						    $var = $this->_em->merge($var);

						    $method = sprintf('set%s', ucfirst($property->getName()));
						    $newContentObject->{$method}($var);
					    }

				    }
			    }
			    $this->_em->persist($newContentObject);
			    $this->_em->flush($newContentObject);


			    $layoutBlock->setObjectId($newContentObject->getId());
		    }

	    }

	    $layoutBlock->setPage($page);

	    $this->_em->persist($layoutBlock);

	    $this->_em->flush($layoutBlock);

	    return $layoutBlock;
    }