Jump to content

Using $cache to cache HTML


a-ok
 Share

Recommended Posts

I tend to use $cache to cache JSON in the database, which is great, but I need to return HTML markup from a JS fetch and I'm unsure how to use PW to return cached HTML.

Below is how I do it for JSON but could anyone lend a hand for HTML?

$segments = array($input->urlSegment1, $input->urlSegment2, $input->urlSegment3);

$data = array();

if ($segments[0] === 'v1' && $segments[1] === 'portfolio') {

	$response = $cache->get('apiPortfolio');
	if (!$response) {
		$portfolio = array();
		$projects = $pages->find("template=project, sort=-date");
		if (count($projects)) {
			foreach ($projects as $project) {
				$portfolio[] = array(
					'id' => $project->id,
					'title' => $project->title
				);
			}
		}
		$response = $portfolio;
		$cache->save('apiPortfolio', $response, "template=portfolio");
	}
	$data['response'] = $response;

} else {
	header('Content-Type: text/html');
	throw new Wire404Exception();
}

$dataJson = wireEncodeJSON($data);

header('Content-Type: application/json');
echo $dataJson;

 

Link to comment
Share on other sites

In your code you are storing an array $portfolio to the cache.

To store HTML you would use the same logic as for storing an array but store an HTML string instead. How you create the HTML string is totally up to you. It could be the return value of a $page->render() call or anything else.

Simplified example

$response = $cache->get('my-html-cache');
	if (!$response) {
		$html = $page->render(); // render a page
		// OR
		$html = $files->render('path-to-template.php'); // render page data with a custom template file
		// OR
		$html = '<h1>Cached Headline</h1>' // simple HTML string
		
		$cache->save('my-html-cache', $html, "template=portfolio");
	}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...