A Mediawiki template can use Magic Words to identify what page it's being transcluded into: {{PAGENAME}}
— and various other details of its namespace. What I can't find out is if there's a Magic Word or some other technique to identify what section (or subsection) of the page* it's being transcluded into.
*i.e. what the headings and subheadings (used to compile the page's table of contents) closest above it are.
Templates need to be context-independent. Currently there are ways to work around that, so you could probably create an extension doing this, but it wouldn't survive the ongoing parser rewrite.