How to get current page ID from inside SS template

Hi There,

I’ve been googling for a while and found nothing so I’m hoping someone here will have an idea.

I’m trying to get the current page id from inside a SS template. Essentially I’m looking for a function or variable to place inside the <% %> tags of the .ss file that will return the id of the page currently being viewed.

Thanks

Hello @Philm, try $ID on the template, this will give the id of the current page where you at.

Hi Jerome,

Thanks for your response. I have tried this but it just throws an error:
“Unexpected problem parsing template”

It’s probably worth noting that I’m working on a component that is added as an include to a page. Essentially what the component does it get a list of 3 related articles however the first of these related articles is always the same as the current article being viewed so I’m trying to exclude it.

Thanks

Hi,

Just to clarify, you just need $ID in the template, not <% $ID %>

But, if you’re pulling in content from a method in your PHP, then it might be better to just put the logic in there, rather than the template (psuedo-code below):

public function getRelatedArticles() {
  return Article::get()->exclude([
    'ID' => $this->ID
  ]);
}

(obviously the logic in that would need to be made right for your application)

Then in your template, you can just do:

<% loop $RelatedArticles %>
 <h2>$Title</h2>
<% end_loop %>

Depending on where you are in your template, e.g. inside a loop, $Up.ID takes the scope back to the previous level. https://docs.silverstripe.org/en/4/developer_guides/templates/syntax/

DorsetDigital is probably offering the better solution for you, but if you wanted to use an if/then statement in your template:

<% loop $RelatedArticles %>
<% if $ID != $Up.ID %>
... show article
<% end_if %>
<% end_loop %>

To get the ID of the page being queried from outside the loop or before the global post object has been set, use get_queried_object_id()

I’m fairly sure that’s not going to work… it’s a Wordpress function!