diff --git a/src/ViewHelpers/InlineViewHelper.php b/src/ViewHelpers/InlineViewHelper.php new file mode 100644 index 000000000..65b2c7426 --- /dev/null +++ b/src/ViewHelpers/InlineViewHelper.php @@ -0,0 +1,62 @@ +assign('variable', 'value of my variable'); + * $view->assign('code', 'My variable: {variable}'); + * + * And in the template: + * + * {code -> f:inline()} + * + * Which outputs: + * + * My variable: value of my variable + * + * You can use this to pass smaller and dynamic pieces of Fluid code + * to templates, as an alternative to creating new partial templates. + */ +class InlineViewHelper extends AbstractViewHelper +{ + use CompileWithContentArgumentAndRenderStatic; + + protected $escapeChildren = false; + + protected $escapeOutput = false; + + /** + * @return void + */ + public function initializeArguments() + { + $this->registerArgument( + 'code', + 'string', + 'Fluid code to be rendered as if it were part of the template rendering it. Can be passed as inline argument or tag content' + ); + } + + /** + * @param array $arguments + * @param \Closure $renderChildrenClosure + * @param RenderingContextInterface $renderingContext + * @return mixed|string + */ + public static function renderStatic( + array $arguments, + \Closure $renderChildrenClosure, + RenderingContextInterface $renderingContext + ) { + return $renderingContext->getTemplateParser()->parse($renderChildrenClosure())->render($renderingContext); + } +} diff --git a/tests/Unit/ViewHelpers/InlineViewHelperTest.php b/tests/Unit/ViewHelpers/InlineViewHelperTest.php new file mode 100644 index 000000000..a8c05d9c0 --- /dev/null +++ b/tests/Unit/ViewHelpers/InlineViewHelperTest.php @@ -0,0 +1,47 @@ +getMockBuilder(InlineViewHelper::class)->setMethods(['registerArgument'])->getMock(); + $instance->expects($this->at(0))->method('registerArgument')->with('code', 'string', $this->anything()); + $instance->initializeArguments(); + } + + /** + * @test + */ + public function testCallsExpectedDelegationMethodFromRenderStatic() + { + $contextFixture = new RenderingContextFixture(); + + $parsedTemplateMock = $this->getMockBuilder(ParsedTemplateInterface::class)->getMock(); + $parsedTemplateMock->expects($this->once())->method('render')->with($contextFixture)->willReturn('bar'); + + $parserMock = $this->getMockBuilder(TemplateParser::class)->setMethods(['parse'])->getMock(); + $parserMock->expects($this->once())->method('parse')->with('foo')->willReturn($parsedTemplateMock); + + $contextFixture->setTemplateParser($parserMock); + + $result = InlineViewHelper::renderStatic([], function() { return 'foo'; }, $contextFixture); + $this->assertEquals('bar', $result); + } +}