Should I save a path with or without a trailing slash at the end, what's the convention

StackOverflow https://stackoverflow.com/questions/17419460

  •  02-06-2022
  •  | 
  •  

Question

I'm always confuse whether I should add a trailing slash at the end of a path, and often mix it up, leading to some file no found. Example with drupal:

$base_theme = '/sites/all/themes/myTheme/';

or

$base_theme = '/sites/all/themes/myTheme';

The image path could extend the base theme:

$base_image = $base_theme.'images/';

or

$base_image = $base_theme.'/images';

Is there any convention? Or I can pick which one I prefer?

I would choose to finish all path with a trailing slash since too many slash is better than no slash.

Was it helpful?

Solution

TL;DR: There's no real convention. Trailing slash would be the more globally easy to recognize format. The important thing is that you're consistent through your design and that you convey your usage clearly.


There's no real convention; but there are considerations to make.

Advantages in trailing slash:

  1. Trailing slash usually indicates a folder path (or a prettified URL) whereas a file extension denotes a direct file link. (Think example.com/home/ VS example.com/style.css).
  2. This is usually friendlier for people coming from UNIX and such, as in the terminal a clear convention is to leave a trailing slash for directories.
  3. As a programmer - adding a trailing slash will result in less-likely programmer errors; for example: accidentally adding a second slash will look ugly (http://example.com/styles//myfile.css) but will not break the file link. Forgetting a slash will: http://example.com/stylesmyfile.css, however the behavior might be confusing for query strings: http://example.com/thread?id=1 VS http://example.com/thread/?id=1 <- the result really depends on how you handle your .htaccess.

Advantages in no trail:

  1. Prettier, some might say
  2. It's easier to remember and it's more readable to always add a slash when appending paths to a variable string than not. i.e. it's easier to remember $baseURL . '/path.php' than $baseURL . 'path.php'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top