Snippet v page model

Hi All

Wondering if somewone could help clear up the difference or rather why/when I would prefer to use one or the other in terms of snippet v page model.

For example, if I wanted to load a particular category image and show on page, for me I see no real difference between creating a snippet to do this and dropping snippet call in, or doing a model and calling a model.

Is noe more advantageous than the other? Am I missing something?

Sorry to act dumb, I’m just trying to work out best “use” of each Kirby feature.

The most obvious difference is that snippets are bits of code that are reusable anywhere, like a header or menu, that you drop into almost all of your templates. Page models on the other hand are just for a particular page or rather page type, i.e. pages that share the same controller and template.

Using a page model IMHO only makes sense if you use a particular method more than once in your template, not for a single call.

Taken together, templates, controllers and models form an MVC (Model-View-Controller) pattern.

to be cont’d.

The difference is that basically the 1:n relationship between pages and templates is turned around:

  • A snippet has a 1:n relationship between the snippet and the pages used by the snippet (so you can access multiple pages, just like in a template)
  • A page model has a n:1 relationship between the template/snippet and the page (the page model’s method can be used in multiple snippets and templates).

So a page model makes sense if your templates have logic (for example a calculation) that is used in multiple snippets and templates (to keep the logic DRY). A snippet makes sense if multiple templates need the same template code (like a header) that isn’t specific to the page’s template.

In order to separate logic and markup, you should try to keep your templates and snippets as simple as possible (meaning to avoid huge amounts of PHP code). You can use snippets if you need to repeat markup blocks in different places on your websites. For example, you might want to include your header and footer in every page.

Sometimes it might also be sensible to use snippets if you have larger blocks of markup that are repeated in loops etc. in order to keep your template clean and readable.

If you need to implement complex logic, use a plugin if the code needs to be shared across multiple templates and use a controller or a page model if it’s template specific.

Hi All

Apologies for not responding sooner.

Wanted to thank you all for your answers - I now somewhat get it :smile:

I’m a bit old school, so still umming and arghing MVC - we use it in work (.Net) but being so used to Wordpress and most Open Source CMS, I’ve never really needed to use it, and got so used to working that way, that I actually find MVC more work to do! lol