Development

HowtoServeStaticContent

You must first sign up to be able to contribute.

Symfony Howto: Serve Static Content

Purpose

If you want serve static content from a single module where the specific content is defined by a parameter, you can easily do this using a partial as seen in the example below.

Method

  • Define a module named static
  • Use the default index action in the module.
  • Create an indexSuccess.php file with a partial
  • Update the executeIndex action.
  • Create a rule in your-app/config/routing.yml
  • Create partials to hold each individual piece of static content

Example

To use a URL like http://localhost/static/about_us:

actions.class.php

<?php
class staticActions extends sfActions
{
	public function executeIndex()
	{
	  $this->content = $this->getRequestParameter('content');
	}
}
?>

indexSuccess.php

<?php include_partial($content); ?>

routing.yml

(add it before default rules)

static:
  url:   /static/:content
  param: { module: static, action: index }

_about_us.php

<table>
  <tr>
    <td>Your specific html here</td>
  </tr>
</table>

Checking if the partial exists from within the action

You may wish to add logic to forward to a 404 page if the static content being requested doesn't exist. This snippet defines a helper function to check if the partial is readable from within the action and forward to the 404 page if not.

actions.class.php

class staticActions extends sfActions {
   public function executeIndex() {
      $this->content = $this->getRequestParameter("content");
         
      $context = $this->getContext();
         
      $this->forward404Unless($this->partialExists($context, $this->content));
   }
      
   protected function partialExists($context, $name) {
      $directory = $context->getModuleDirectory();
                                                     
      if (is_readable($directory . DIRECTORY_SEPARATOR ."templates". DIRECTORY_SEPARATOR ."_". $name .".php")) {
         return true;
      } else {
         return false;
      }
   }
}

Credits

This page was culled from the forum question and responses by davedash and Ian