Fix rel canonical link (#2126)
* Fix rel canonical link
* Verify files at different levels in test
diff --git a/lib/src/html/template_data.dart b/lib/src/html/template_data.dart
index 464bff6..4ba0930 100644
--- a/lib/src/html/template_data.dart
+++ b/lib/src/html/template_data.dart
@@ -2,7 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import 'package:dartdoc/src/render/template_renderer.dart';
import 'package:dartdoc/src/model/model.dart';
abstract class HtmlOptions {
@@ -40,6 +39,13 @@
String get relCanonicalPrefix => htmlOptions.relCanonicalPrefix;
bool get useBaseHref => htmlOptions.useBaseHref;
+ String get bareHref {
+ if (self is Indexable) {
+ return (self as Indexable).href.replaceAll(HTMLBASE_PLACEHOLDER, '');
+ }
+ return '';
+ }
+
String _layoutTitle(String name, String kind, bool isDeprecated) =>
packageGraph.rendererFactory.templateRenderer
.composeLayoutTitle(name, kind, isDeprecated);
diff --git a/lib/templates/_head.html b/lib/templates/_head.html
index 5c5e9db..3cfa7a3 100644
--- a/lib/templates/_head.html
+++ b/lib/templates/_head.html
@@ -10,7 +10,7 @@
<meta name="description" content="{{ metaDescription }}">
<title>{{ title }}</title>
{{ #relCanonicalPrefix }}
- <link rel="canonical" href="{{{relCanonicalPrefix}}}/{{{self.href}}}">
+ <link rel="canonical" href="{{{relCanonicalPrefix}}}/{{{bareHref}}}">
{{ /relCanonicalPrefix}}
{{#useBaseHref}}{{! TODO(jdkoren): remove when the useBaseHref option is removed.}}
diff --git a/test/dartdoc_test.dart b/test/dartdoc_test.dart
index 2b393bd..7a3339e 100644
--- a/test/dartdoc_test.dart
+++ b/test/dartdoc_test.dart
@@ -406,5 +406,24 @@
expect(e is DartdocFailure, isTrue);
}
});
+
+ test('rel canonical prefix does not include base href', () async {
+ final String prefix = 'foo.bar/baz';
+ Dartdoc dartdoc = await buildDartdoc(
+ ['--rel-canonical-prefix', prefix], testPackageDir, tempDir);
+ await dartdoc.generateDocsBase();
+
+ // Verify files at different levels have correct <link> content.
+ File level1 = File(path.join(tempDir.path, 'ex', 'Apple-class.html'));
+ expect(level1.existsSync(), isTrue);
+ expect(
+ level1.readAsStringSync(),
+ contains(
+ '<link rel="canonical" href="$prefix/ex/Apple-class.html">'));
+ File level2 = File(path.join(tempDir.path, 'ex', 'Apple', 'm.html'));
+ expect(level2.existsSync(), isTrue);
+ expect(level2.readAsStringSync(),
+ contains('<link rel="canonical" href="$prefix/ex/Apple/m.html">'));
+ });
}, timeout: Timeout.factor(8));
}