Skip to content

Commit 23ad8da

Browse files
authored
Add WebView::renderAjaxString() (#141)
1 parent 9711c03 commit 23ad8da

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

src/WebView.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,28 @@ public function renderAjax(string $view, array $params = []): string
236236
return ob_get_clean();
237237
}
238238

239+
/**
240+
* Renders a string in response to an AJAX request.
241+
*
242+
* @param string $string The string.
243+
*
244+
* @return string The rendering result.
245+
*/
246+
public function renderAjaxString(string $string): string
247+
{
248+
ob_start();
249+
PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
250+
251+
$this->beginPage();
252+
$this->head();
253+
$this->beginBody();
254+
echo $string;
255+
$this->endBody();
256+
$this->endPage(true);
257+
258+
return ob_get_clean();
259+
}
260+
239261
/**
240262
* Clears up the registered meta tags, link tags, css/js scripts and files.
241263
*/

tests/WebViewTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
use Yiisoft\Files\FileHelper;
1212
use Yiisoft\Html\Html;
1313
use Yiisoft\Test\Support\EventDispatcher\SimpleEventDispatcher;
14+
use Yiisoft\View\Event\BodyBegin;
15+
use Yiisoft\View\Event\BodyEnd;
16+
use Yiisoft\View\Event\PageBegin;
1417
use Yiisoft\View\Event\PageEnd;
1518
use Yiisoft\View\WebView;
1619

@@ -140,6 +143,26 @@ public function testRenderAjaxWithoutContext(): void
140143
$this->assertSame($content, $html);
141144
}
142145

146+
public function testRenderAjaxString(): void
147+
{
148+
$eventDispatcher = new SimpleEventDispatcher();
149+
$webView = $this->createWebView($eventDispatcher);
150+
151+
$string = 'content';
152+
$result = $webView->renderAjaxString($string);
153+
154+
$this->assertSame($string, $result);
155+
$this->assertSame(
156+
[
157+
PageBegin::class,
158+
BodyBegin::class,
159+
BodyEnd::class,
160+
PageEnd::class,
161+
],
162+
$eventDispatcher->getEventClasses()
163+
);
164+
}
165+
143166
public function testRegisterScriptTag(): void
144167
{
145168
$script = Html::script('{"@context": "http://schema.org/","@type": "Article","name": "Yii 3"}')

0 commit comments

Comments
 (0)