From eca537347f26f83ff53df5f3edeea654e6a925a0 Mon Sep 17 00:00:00 2001 From: Abram Booth Date: Thu, 17 May 2018 16:14:40 -0400 Subject: [PATCH] Add support for routable engines Make {{href-to}} behave the same as {{link-to}} within an engine, automatically prefixing routes with the engine's namespace Add {{href-to-external}}, for routes external to the engine. --- addon/helpers/href-to-external.js | 22 ++++++++++++++++++++++ addon/helpers/href-to.js | 14 ++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 addon/helpers/href-to-external.js diff --git a/addon/helpers/href-to-external.js b/addon/helpers/href-to-external.js new file mode 100644 index 0000000..b5f67ff --- /dev/null +++ b/addon/helpers/href-to-external.js @@ -0,0 +1,22 @@ +import Helper from '@ember/component/helper'; +import { getOwner } from '@ember/application'; +import { getHrefFromOwner } from './href-to'; + +function hrefToExternal(context, targetRouteName, ...rest) { + const owner = getOwner(context); + + if(owner.mountPoint) { + targetRouteName = owner._getExternalRoute(targetRouteName); + } + return getHrefFromOwner(owner, targetRouteName, ...rest); +} + +export default Helper.extend({ + compute([targetRouteName, ...rest], namedArgs) { + if(namedArgs.params) { + return hrefToExternal(this, ...namedArgs.params); + } else { + return hrefToExternal(this, targetRouteName, ...rest); + } + } +}); diff --git a/addon/helpers/href-to.js b/addon/helpers/href-to.js index ac18bfd..ae808b2 100644 --- a/addon/helpers/href-to.js +++ b/addon/helpers/href-to.js @@ -2,7 +2,17 @@ import Helper from '@ember/component/helper'; import { getOwner } from '@ember/application'; function hrefTo(context, targetRouteName, ...rest) { - let router = getOwner(context).lookup('service:router'); + let owner = getOwner(context); + + // If used in an engine, namespace the route + if(owner.mountPoint && targetRouteName !== 'application') { + targetRouteName = `${owner.mountPoint}.${targetRouteName}`; + } + return getHrefFromOwner(owner, targetRouteName, ...rest); +} + +function getHrefFromOwner(owner, targetRouteName, ...rest) { + let router = owner.lookup('service:router'); if(router === undefined) { return; @@ -22,7 +32,7 @@ function hrefTo(context, targetRouteName, ...rest) { return router.urlFor.apply(router, args); } -export { hrefTo }; +export { hrefTo, getHrefFromOwner }; export default Helper.extend({ compute([targetRouteName, ...rest], namedArgs) {