diff --git a/src/View/Input/Label.php b/src/View/Input/Label.php new file mode 100644 index 00000000000..d9734103a30 --- /dev/null +++ b/src/View/Input/Label.php @@ -0,0 +1,69 @@ +_templates = $templates; + } + +/** + * Render a label widget. + * + * Accepts the following keys in $data: + * + * - `text` The text for the label. + * - `input` The input that can be formatted into the label if the template allows it. + * - `escape` Set to false to disable HTML escaping. + * + * All other attributes will be converted into HTML attributes. + * + * @param array $data + * @return string + */ + public function render($data) { + $data += [ + 'text' => '', + 'input' => '', + 'escape' => true, + ]; + + return $this->_templates->format('label', [ + 'text' => $data['escape'] ? h($data['text']) : $data['text'], + 'input' => $data['input'], + 'attrs' => $this->_templates->formatAttributes($data, ['text', 'input']), + ]); + } + +} diff --git a/tests/TestCase/View/Input/LabelTest.php b/tests/TestCase/View/Input/LabelTest.php new file mode 100644 index 00000000000..4ca466619a0 --- /dev/null +++ b/tests/TestCase/View/Input/LabelTest.php @@ -0,0 +1,101 @@ + '{{text}}', + ]; + $this->templates = new StringTemplate($templates); + } + +/** + * test render + * + * @return void + */ + public function testRender() { + $label = new Label($this->templates); + $data = [ + 'text' => 'My text', + ]; + $result = $label->render($data); + $expected = [ + 'label' => [], + 'My text', + '/label' + ]; + $this->assertTags($result, $expected); + } + +/** + * test render escape + * + * @return void + */ + public function testRenderEscape() { + $label = new Label($this->templates); + $data = [ + 'text' => 'My > text', + 'for' => 'Some > value', + 'escape' => false, + ]; + $result = $label->render($data); + $expected = [ + 'label' => ['for' => 'Some > value'], + 'My > text', + '/label' + ]; + $this->assertTags($result, $expected); + } + +/** + * test render escape + * + * @return void + */ + public function testRenderAttributes() { + $label = new Label($this->templates); + $data = [ + 'text' => 'My > text', + 'for' => 'some-id', + 'id' => 'some-id', + 'data-foo' => 'value', + ]; + $result = $label->render($data); + $expected = [ + 'label' => ['id' => 'some-id', 'data-foo' => 'value', 'for' => 'some-id'], + 'My > text', + '/label' + ]; + $this->assertTags($result, $expected); + } + +}