Use add_action within template

There is no limitation to using add_action(), except that core must have it loaded already. Practically this means pretty much anywhere, but wp-config.php.

While it is possible to do it in template, it’s not a common practice because of:

  1. Timing issues (your template part might be loaded after the hooks you need).
  2. Code base clarity (it would be hard for someone else to find and make sense of it spread all around).

The typical practice is to:

  1. Create intermediary function.
  2. Hook it to appropriate hook (late enough for things to work, not too late), this is often init, admin_init, or template_redirect.
  3. Check the current context with conditional functions and on match hooks the other functions as you need.

This approach keeps things compact and easy for developers to both study and modify the behavior.
3.