Thursday, November 13, 2008

Autodiscover new pages using the server's directory index

Needed to have website pages listed in a side bar of the main page, when they are created in a certain directory. Wanted to do it without any additional server-side software. jQuery to the rescue.

First, enable the directory autoindex in NGINX. Add this to the nginx.conf:

location /drop_dir/ {
    autoindex on;
}

Then use the script from here:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Directory query example</title>
    <script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
    <script type="text/javascript" charset="utf-8">
      $(document).ready(function() {
        $.get( "/drop_dir/", function (data) {
          $(data).find('a')
          .filter('[href$=".html"]:not("[href^=.]"):not("[href^=?]")')
          .each( function(){
            page = $(this).attr('href');
            $('<li>').appendTo('#examples').prepend(
              $('<a>').attr('href', '/drop_dir/' + page ).text( page )
            );
          });
        });
      });
    </script>
    <style type="text/css" media="screen">
      #examples {
        list-style-type: none;
      }
    </style>
  </head>
  <body>
    <ul id="examples" />
  </body>
</html>

Notice, that URLs starting with dots and question marks are filtered out, and only pages full .html extensions are selected. Adjust to your taste. Needless to say that the there should be no index.html, or similar, file, or the default index file should be de-configured for that directory.

Should not be too hard to adjust for apache, either.

jQuery rules :)

read more ...