Code coverage report for template/index.js

Statements: 99.74% (781 / 783)      Branches: 94.94% (338 / 356)      Functions: 100% (120 / 120)      Lines: 99.74% (773 / 775)      Ignored: none     

All files » template/ » index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312                  1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1 1 1 1 1 1 1 1 1 1                                   1   484 484 484               1 1 1               1 484 484 484 484 484     484 484 484     484 484 484 484     484 484 484 484 484 484   484                 1 484 484 484 484 484 484 484                 1 484 484 484 484                 1 484                 1 484 484 484 484 484   484 484 484 484 484 484 484 484 484 484 484 484 484 484     484 1       484 625               1 6                       1 484 484 651 651 650                                 1 484 484                               1 484                       1 1661                 1 484 484 484                                               1 486   486 1     485 1     484   484 484     484                   1 1147 484         484                       1 1054   1054 22     1054 1054   1054 1 1 1     1053                     1 637 651 651 651 1 1                                 1 5 5     5 5   5 1       5 5 5       5 5 1     4 4   4   6 5     1 1 1     4                           1 505 505   505                             1 3   3   3 1 2   1     2 2                       1 3 6 6   6 6   6 6                           1 2 2   2 2   2 2                       1 265     265 49     216   216 37       216       216 216 1 1   1     216     216 216                                   1 513   513   513 1     512 512                                                   1 511 498     511 511     511 484   27 27     511 511   511 511                     1 216   216 1     216 34     182 182                             1 13   13 13     13                             1   204             204           204 2 2   2         204 12                             1 1164   1164 1164 1160     1164   1164 1 1   1164                               1 661 661 1164   661                               1 423 423                                               1 1035   1035 1     1034     1034                   1034 1033 365   1033                                 1 6   6 1     5 1     4 4                                 1 6   6 1     5 1     4 4                                           1 539 539 539                                   1 7   7 4 3   3 2 3     1 1 3 3 3         7                                             1 539 539 539                                   1 3 3 3                             1 9 9                     1 537 537   537 8 8   8   1 1     7   7 7 1   6                       1 537 537   537 17   17 17 9 9     17 2     17   17   1 1     16 16   16 16 15 15                           1 635 635   635 635 635   635 635 635   635 4     635 635   635         635 1946     635 4       635     635   635 635 635     635   635 635         635                       1 1670 1670     1670 1661     1670   1 638 3 3   3   635       1670 638 638 638 638   638 5     638 638     636       636         650 650 9 9 7   9   650 4     650 6         636     636 636     638 638                         1 640 1     640 653       653 1     653 2     653 2                                 1 627 627   627 1     626 637 637   637 637   626                           1 1944 8 8 3   5   1936                         1 1670 1670     1670   1670 607     1670 531     1670 537 537   1670                                     1 418 418   418 581 581                                 1 399 399   399 399 399 399   399 498 498 472 472       399                           1 234   234 234   234 2     232 11 221 4   217   232 107   232                                             1 195   195 195 1     194 194     194 201     201 61 61     61 59       2 2         194 194                           1 164   164 148     16 1                               1 143                             1 3                             1 11                         1 24   24 19     5 2     3 1     2 2                                         1 1670           1670 1605 1605 1605     1670 10     1670 1661     1670   1670 1670     1670           1670   1670   537 537       537 537     1670                       1 1670             1670           1670 638             1670 550             1670 17             1670 1                             1 206 206 1   205 205   1 1                           1 205 205   205 1         204 204 204   204 204     204 204     204     204 204 36       204 204     204 204     204                         1 16   16 1     15 5     10 10 5     5                               1 5 5 1 1     5 5   5 5                             1 196 196 2 2     196 64     132                         1 194 194 194 64 64   194 2       192 192     192 192     192 192     192 192     192     192 189 189 189 189     192 192     192 179               192 62     62 62               130 130 127 127 127                             1 64 1   63 63   1 1                               1 132 1     131 131 131 130 2 2 2     128 128 1 1     127       1 1                         1 147   147 2     145 20     125 125 116     9                             1 17 17 1 1     17 17   17 17                                   1 19     19 19   19 19 19 2 2       19 19 1   18                         1 7 7   7 7 7 6 6     7 7 1   6                               1 204   204 204 204   204 127   204   204 204 204   204                                     1 193 1     192 192     192 12 12   180 180       192     192 192 192 192                                 1 168 168                     1 381 381 3 3                               1 3340                         1 6680                         1 1              
/*!
 * template <https://github.com/jonschlinkert/template>
 *
 * Copyright (c) 2014 Jon Schlinkert, Brian Woodward
 * Licensed under the MIT license.
 */
 
'use strict';
 
var _ = require('lodash');
var path = require('path');
var glob = require('globby');
var chalk = require('chalk');
var Delims = require('delims');
var forOwn = require('for-own');
var typeOf = require('kind-of');
var layouts = require('layouts');
var routes = require('en-route');
var Cache = require('config-cache');
var Helpers = require('helper-cache');
var Engines = require('engine-cache');
var arrayify = require('arrayify-compact');
var engineLodash = require('engine-lodash');
var EscapeDelims = require('escape-delims');
var parser = require('parser-front-matter');
var flatten = require('arr-flatten');
var slice = require('array-slice');
var arr = require('arr');
 
var init = require('./lib/middleware/init');
var defaultLoader = require('./lib/loaders');
var camelize = require('./lib/camelize');
var hasOwn = require('./lib/has-own');
var debug = require('./lib/debug');
var utils = require('./lib');
var Router = routes.Router;
var Route = routes.Route;
var extend = _.extend;
var merge = _.merge;
 
/**
 * Create a new instance of `Template`, optionally passing
 * default `options` to initialize with.
 *
 * **Example:**
 *
 * ```js
 * var Template = require('template');
 * var template = new Template();
 * ```
 *
 * @class `Template`
 * @param {Object} `options` Options to initialize with.
 * @api public
 */
 
var Template = module.exports = Cache.extend({
  constructor: function(options) {
    Template.__super__.constructor.call(this, options);
    this.initTemplate();
    this.loadDefaults();
  }
});
 
/**
 * Extend `Template`
 */
 
Template.extend = Cache.extend;
Template.Router = Router;
Template.Route = Route;
 
/**
 * Initialize defaults.
 *
 * @api private
 */
 
Template.prototype.initTemplate = function() {
  this.loaders = this.loaders || {};
  this.engines = this.engines || {};
  this.delims = this.delims || {};
  this.layoutSettings = {};
  this.transforms = {};
 
  // Engine properties
  this._ = {};
  this._.mixins = {};
  this._.imports = {};
 
  // View types (categories)
  this.type = {};
  this.type.partial = [];
  this.type.renderable = [];
  this.type.layout = [];
 
  // View collections
  this.views = {};
  this.view('layouts', {});
  this.view('partials', {});
  this.view('anonymous', {});
  this.view('pages', {});
  this.collection = {};
 
  this.set('_context', {});
};
 
/**
 * Load all defaults
 *
 * @api private
 */
 
Template.prototype.loadDefaults = function() {
  this.defaultConfig();
  this.defaultOptions();
  this.defaultRoutes();
  this.defaultTransforms();
  this.defaultDelimiters();
  this.defaultTemplates();
  this.defaultEngines();
};
 
/**
 * Initialize the default configuration.
 *
 * @api private
 */
 
Template.prototype.defaultConfig = function() {
  this._.delims = new Delims(this.options);
  this._.engines = new Engines(this.engines);
  this._.helpers = new Helpers({bind: false});
  this._.asyncHelpers = new Helpers({bind: false});
};
 
/**
 * Run the default transforms.
 *
 * @api private
 */
 
Template.prototype.defaultTransforms = function() {
  this.transform('placeholder', function () {});
};
 
/**
 * Initialize default options.
 *
 * @api private
 */
 
Template.prototype.defaultOptions = function() {
  this.disable('debugEngine');
  this.disable('preferLocals');
  this.enable('default engines');
  this.enable('default helpers');
  this.enable('default routes');
 
  this.option('cwd', process.cwd());
  this.option('ext', '*');
  this.option('destExt', '.html');
  this.option('defaultExts', ['md', 'html', 'hbs', 'lodash']);
  this.option('delims', ['<%', '%>']);
  this.option('viewEngine', '*');
  this.enable('mergePartials');
  this.enable('mergeLayouts');
  this.option('defaultLayout', null);
  this.option('layoutDelims', ['{%', '%}']);
  this.option('layoutTag', 'body');
  this.option('layoutExt', null);
  this.option('layout', null);
  this.option('router methods', []);
 
  // Custom function for naming partial keys
  this.option('partialsKey', function (fp) {
    return path.basename(fp, path.extname(fp));
  });
 
  // Custom function for all other template keys
  this.option('renameKey', function (fp) {
    return path.basename(fp);
  });
};
 
/**
 * Set the current working directory
 */
 
defineGetter(Template.prototype, 'cwd', function () {
  return this.option('cwd') || process.cwd();
});
 
/**
 * Load default routes / middleware
 *
 *   - `.md`: parse front matter in markdown files
 *   - `.hbs`: parse front matter in handlebars templates
 *
 * @api private
 */
 
Template.prototype.defaultRoutes = function() {
  Eif (this.enabled('default routes')) {
    this.route(/\.*/).onLoad(function route(file, next) {
      parser.parse(file, function(err) {
        if (err) return next(err);
        next();
      });
    });
  }
};
 
/**
 * Load default engines.
 *
 *   - `*` The noop engine is used as a pass-through when no other engine matches.
 *   - `md|html|hbs`. [engine-lodash] will process templates  in any files with these
 *                    extensions. To change or negate these extensions, just do
 *                    `engine.option('defaultExts', ['foo', 'bar', 'baz'])`.
 *
 * @api private
 */
 
Template.prototype.defaultEngines = function() {
  Eif (this.enabled('default engines')) {
    this.engine(['*', 'md'], engineLodash, {
      layoutDelims: ['{%', '%}'],
      destExt: '.html'
    });
  }
};
 
/**
 * Register default template delimiters.
 *
 *   - engine delimiters: Delimiters used in templates process by [engine-lodash], the default engine.
 *   - layout delimiters: Delimiters used in layouts.
 *
 * @api private
 */
 
Template.prototype.defaultDelimiters = function() {
  this.addDelims('*', ['<%', '%>'], ['{%', '%}']);
};
 
/**
 * Default loader to use when a user-defined loader is
 * not given for a template collection.
 *
 * @param {String} `plural` The collection name, e.g. `pages`
 * @param {Object} `options`
 * @api private
 */
 
Template.prototype.defaultLoader = function(plural, options) {
  return [defaultLoader.call(this, plural, options)];
};
 
/**
 * Register default view collections.
 *
 * @api private
 */
 
Template.prototype.defaultTemplates = function() {
  this.create('page', { isRenderable: true });
  this.create('layout', { isLayout: true });
  this.create('partial', { isPartial: true });
};
 
/**
 * Assign transform `fn` to `name` or return the value of `name`
 * if no other arguments are passed.
 *
 * Transforms are run immediately during init, and are used to
 * extend or modify the `cache.data` object, but really anything
 * on the `this` object can be tranformed.
 *
 * ```js
 * template.transform('username', function(app) {
 *   var url = app.cache.data.author.url.split('/');
 *   app.cache.data.username = url[2];
 * });
 * ```
 *
 * @param {String} `name` The name of the transform to add.
 * @param {Function} `fn` The actual transform function.
 * @return {Object} Returns `Template` for chaining.
 * @api private
 */
 
Template.prototype.transform = function(name, fn) {
  debug.engine('adding [transform]: %s', name);
 
  if (arguments.length === 0) {
    return this.transforms;
  }
 
  if (arguments.length === 1) {
    return this.transforms[name];
  }
 
  this.transforms[name] = fn;
 
  Eif (fn && typeof fn === 'function') {
    fn.apply(this, [this].concat(arguments));
  }
 
  return this;
};
 
/**
 * Lazily initalize router, to allow options to
 * be passed in after init.
 *
 * @api private
 */
 
Template.prototype.lazyrouter = function() {
  if (!this.router) {
    this.router = new Router({
      caseSensitive: this.enabled('case sensitive routing'),
      strict: this.enabled('strict routing'),
      methods: utils.methods.concat(this.option('router methods'))
    });
    this.router.use(init(this));
  }
};
 
/**
 * Dispatch `file` through its middleware stack
 *
 * @param {String} `method` method to dispatch files to (undefined will dispatch to `all`)
 * @param  {Object} `file` File object to be passed through the middleware stack
 * @api private
 */
 
Template.prototype.handle = function(method, file, done) {
  debug.routes('handling: %j', arguments);
 
  if (typeof method === 'object') {
    done = file; file = method; method = null;
  }
 
  file.options = file.options || {};
  file.options.method = method;
 
  if (!this.router) {
    debug.routes('no routes defined on engine');
    done();
    return;
  }
 
  this.router.handle(file, done);
};
 
/**
 * Dispatch `file` through an explicitly defined middleware `stack`.
 *
 * @param  {Object} `file`
 * @param  {Array} `fns`
 * @api private
 */
 
Template.prototype.dispatch = function(file, fns) {
  forOwn(file, function (value, key) {
    if (fns) this.route(value.path).all(fns);
    this.handle('onLoad', value, function (err) {
      if (err) {
        console.log(chalk.red('Error running middleware for', key));
        console.log(chalk.red(err));
      }
    });
  }.bind(this));
};
 
/**
 * Proxy to `Router#use()` to add middleware to the engine router.
 * See Router#use() documentation for details.
 *
 * If the `fn` parameter is an engine, then it will be
 * mounted at the `route` specified.
 *
 * @param {Function} `fn`
 * @api public
 */
 
Template.prototype.use = function (fn) {
  var offset = 0;
  var path = '/';
 
  // default path to '/'
  Eif (typeof fn !== 'function') {
    var arg = fn;
 
    while (Array.isArray(arg) && arg.length !== 0) {
      arg = arg[0];
    }
 
    // first arg is the path
    Eif (typeof arg !== 'function') {
      offset = 1;
      path = fn;
    }
  }
 
  var fns = flatten(slice(arguments, offset));
  if (fns.length === 0) {
    throw new TypeError('Template#use() expects middleware functions');
  }
 
  this.lazyrouter();
  var router = this.router;
 
  fns.forEach(function (fn) {
    // non-Template instance
    if (!fn || !fn.handle || !fn.set) {
      return router.use(path, fn.bind(this));
    }
 
    debug.routes('use: %s', path);
    fn.mountpath = path;
    fn.parent = this;
  }, this);
 
  return this;
};
 
/**
 * Proxy to the engine `Router#route()`
 * Returns a new `Route` instance for the `path`.
 *
 * Routes are isolated middleware stacks for specific paths.
 * See the Route api docs for details.
 *
 * @param {String} `path`
 * @api public
 */
 
Template.prototype.route = function(path) {
  debug.routes('route: %s', path);
  this.lazyrouter();
 
  return this.router.route(path);
};
 
/**
 * Proxy to `Router#param()` with one added api feature. The `name` parameter
 * can be an array of names.
 *
 * See the Router#param() docs for more details.
 *
 * @param {String|Array} `name`
 * @param {Function} `fn`
 * @return {Object} `Template` for chaining
 * @api public
 */
 
Template.prototype.param = function(name, fn) {
  debug.routes('param: %s', name);
 
  this.lazyrouter();
 
  if (Array.isArray(name)) {
    name.forEach(function(key) {
      this.param(key, fn);
    }, this);
    return this;
  }
 
  this.router.param(name, fn);
  return this;
};
 
/**
 * Delegate `.METHOD(...)` calls to `router.METHOD(...)`
 *
 * @param {String} `path`
 * @param {Function} Callback
 * @return {Object} `Template` for chaining
 * @api public
 */
 
utils.methods.forEach(function(method) {
  Template.prototype[method] = function(path) {
    debug.routes('$s: $s', method, path);
    this.lazyrouter();
 
    var route = this.router.route(path);
    var args = slice(arguments, 1);
 
    route[method].apply(route, args);
    return this;
  };
});
 
/**
 * Special-cased "all" method, applying the given route `path`,
 * middleware, and callback.
 *
 * @param {String} `path`
 * @param {Function} Callback
 * @return {Object} `Template` for chaining
 * @api public
 */
 
Template.prototype.all = function(path) {
  debug.routes('all: %s', path);
  this.lazyrouter();
 
  var route = this.router.route(path);
  var args = slice(arguments, 1);
 
  route.all.apply(route, args);
  return this;
};
 
/**
 * If a layout is defined, apply it. Otherwise just return the content as-is.
 *
 * @param  {String} `ext` The layout settings to use.
 * @param  {Object} `template` Template object, with `content` to be wrapped with a layout.
 * @return  {String} Either the string wrapped with a layout, or the original string if no layout was found.
 * @api private
 */
 
Template.prototype.applyLayout = function(template, locals) {
  debug.layout('applying layout: %j', arguments);
 
  // If a layout has already been applied, return the content
  if (template.options.layoutApplied) {
    return template.content;
  }
 
  template.options.layoutApplied = true;
 
  if (template.options.isPartial) {
    locals.defaultLayout = false;
  }
 
  // Get the name of the (starting) layout to be used
  var layout = utils.getLayout(template, locals);
 
  // If `layoutExt` is defined on the options, append
  // it to the layout name before passing the name to [layouts]
  var ext = this.option('layoutExt');
  if (ext) {
    Eif (ext[0] !== '.') {
      ext = '.' + ext;
    }
    layout = layout + ext;
  }
 
  locals.delims = locals.layoutDelims || locals.delims;
 
  // Merge `layout` collections based on settings
  var stack = this.mergeLayouts(locals);
  return layouts(template.content, layout, stack, locals);
};
 
/**
 * Pass custom delimiters to Lo-Dash.
 *
 * **Example:**
 *
 * ```js
 * template.makeDelims(['{%', '%}'], ['{{', '}}'], opts);
 * ```
 *
 * @param  {Array} `arr` Array of delimiters.
 * @param  {Array} `layoutDelims` layout-specific delimiters to use. Default is `['{{', '}}']`.
 * @param  {Object} `options` Options to pass to [delims].
 * @api private
 */
 
Template.prototype.makeDelims = function(arr, options) {
  var settings = extend({}, options, { escape: true });
 
  debug.delims('making delims: %j', arr);
 
  if (!Array.isArray(arr)) {
    return merge(options, this.getDelims('*'));
  }
 
  var delims = this._.delims.templates(arr, settings);
  return merge({}, delims, options);
};
 
/**
 * Cache delimiters by `name` with the given `options` for later use.
 *
 * **Example:**
 *
 * ```js
 * template.addDelims('curly', ['{%', '%}']);
 * template.addDelims('angle', ['<%', '%>']);
 * template.addDelims('es6', ['${', '}'], {
 *   // override the generated regex
 *   interpolate: /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g
 * });
 * ```
 *
 * [delims]: https://github.com/jonschlinkert/delims "Generate regex for delimiters"
 *
 * @param {String} `name` The name to use for the stored delimiters.
 * @param {Array} `delims` Array of delimiter strings. See [delims] for details.
 * @param {Object} `opts` Options to pass to [delims]. You can also use the options to
 *                        override any of the generated delimiters.
 * @api public
 */
 
Template.prototype.addDelims = function(ext, delims1, delims2, settings) {
  if (ext[0] !== '.') {
    ext = '.' + ext;
  }
 
  debug.delims('adding delims [ext]: %s', ext, delims1);
  var opts = {};
 
 
  if (Array.isArray(delims2)) {
    opts.layoutDelims = delims2;
  } else {
    settings = delims2;
    delims2 = this.option('layoutDelims');
  }
 
  extend(opts, this.makeDelims(delims1, settings));
  extend(opts, settings);
 
  this.delims[ext] = opts;
  return this;
};
 
/**
 * The `ext` of the stored delimiters to pass to the current delimiters engine.
 * The engine must support custom delimiters for this to work.
 *
 * @param  {Array} `ext` The name of the stored delimiters to pass.
 * @api private
 */
 
Template.prototype.getDelims = function(ext) {
  debug.delims('getting delims: %s', ext);
 
  if (ext && ext[0] !== '.') {
    ext = '.' + ext;
  }
 
  if(hasOwn(this.delims, ext)) {
    return this.delims[ext];
  }
 
  ext = this.currentDelims || '.default';
  return this.delims[ext];
};
 
/**
 * Specify by `ext` the delimiters to make active.
 *
 * ```js
 * template.useDelims('curly');
 * template.useDelims('angle');
 * ```
 *
 * @param {String} `ext`
 * @api public
 */
 
Template.prototype.useDelims = function(ext) {
  debug.delims('using delims: %s', ext);
 
  Eif (ext && ext[0] !== '.') {
    ext = '.' + ext;
  }
 
  return this.currentDelims = ext;
};
 
/**
 * Specify by `ext` the delimiters to make active.
 *
 * ```js
 * template.useDelims('curly');
 * template.useDelims('angle');
 * ```
 *
 * @param {String} `ext`
 * @api public
 */
 
Template.prototype.handleDelims = function(ext, engine, template, locals) {
  // See if delimiters are defined for the template
  var delims = template.delims
    || template.options.delims
    || locals.delims
    || engine.options && engine.options.delims;
 
 
  // See if escape syntax is defined for delimiters
  var escapeDelims = template.escapeDelims
    || template.options.escapeDelims
    || locals.escapeDelims
    || engine.options && engine.options.escapeDelims
    || this.option('escapeDelims');
 
  if (escapeDelims && typeof escapeDelims === 'object') {
    Eif (Array.isArray(escapeDelims)) {
      escapeDelims = {from: escapeDelims, to: delims};
    }
    locals.escapeDelims = escapeDelims;
  }
 
  // Ensure that delimiters are converted to regex and
  // cached, so we can pass the regex to the engine
  if (Array.isArray(delims)) {
    this.addDelims(ext, delims);
  }
};
 
/**
 * Private method for registering an engine. Register the given view
 * engine callback `fn` as `ext`.
 *
 * @param {String} `ext`
 * @param {Function|Object} `fn` or `options`
 * @param {Object} `options`
 * @return {Object} `Template` to enable chaining
 * @api private
 */
 
Template.prototype.registerEngine = function(ext, fn, options) {
  debug.engine('registering [engine]: %s', ext);
 
  var opts = extend({}, options);
  if (ext[0] !== '.') {
    ext = '.' + ext;
  }
 
  this._.engines.setEngine(ext, fn, opts);
 
  if (opts.delims) {
    this.addDelims(ext, opts.delims);
    this.engines[ext].delims = this.getDelims(ext);
  }
  return this;
};
 
/**
 * Register the given view engine callback `fn` as `ext`. If only `ext`
 * is passed, the engine registered for `ext` is returned. If no `ext`
 * is passed, the entire cache is returned.
 *
 * @doc api-engine
 * @param {String|Array} `exts` File extension or array of extensions.
 * @param {Function|Object} `fn` or `options`
 * @param {Object} `options`
 * @return {Object} `Template` to enable chaining
 * @api public
 */
 
Template.prototype.engine = function(exts, fn, options) {
  debug.engine('engine %j:', exts);
  arrayify(exts).forEach(function(ext) {
    this.registerEngine(ext, fn, options);
  }.bind(this));
  return this;
};
 
/**
 * Get the engine settings registered for the given `ext`.
 *
 * ```js
 * template.getEngine('.html');
 * ```
 *
 * @doc api-getEngine
 * @param {String} `ext` The engine to get.
 * @return {Object} Object with methods and settings for the specified engine.
 * @api public
 */
 
Template.prototype.getEngine = function(ext) {
  debug.engine('getting [engine]: %s', ext);
  return this._.engines.getEngine(ext);
};
 
/**
 * Used in the `.render()` method to select the `ext`
 * to use for picking an engine.
 *
 * This logic can be overridden by passing a custom
 * function on `options.getExt`, e.g.:
 *
 * **Example:**
 *
 * ```js
 * template.option('getExt', function(template, locals) {
 *   return path.extname(template.path);
 * });
 * ```
 *
 * @param {Object} `template` Template object
 * @param {Object} `locals` Locals object
 * @return {String} `ext` For determining the engine to use.
 * @api public
 */
 
Template.prototype.getExt = function(template, locals) {
  var fn = this.option('getExt');
 
  if (typeof fn === 'function') {
    return fn.call(this, template, locals);
  }
 
  template.locals = template.locals || {};
 
  // `_engine` is defined on the `.create()` method
  var ext = template.options._engine
    || template.locals.engine
    || template.options.engine
    || locals.engine
    || locals.ext
    || template.engine
    || template.ext
    || path.extname(template.path)
    || this.option('viewEngine');
 
  if (ext == null) return null;
  if (ext[0] !== '.') {
    ext = '.' + ext;
  }
  return ext;
};
 
/**
 * Assign mixin `fn` to `name` or return the value of `name`
 * if no other arguments are passed.
 *
 * This method sets mixins on the cache, which can later be passed
 * to any template engine that uses mixins, like Lo-Dash or Underscore.
 * This also ensures that mixins are passed to the same instance of
 * whatever engine is used.
 *
 * @param {String} `name` The name of the mixin to add.
 * @param {Function} `fn` The actual mixin function.
 * @api private
 */
 
Template.prototype.mixin = function(name, fn) {
  debug.engine('adding [mixin]: %s', name);
 
  if (arguments.length === 0) {
    return this._.mixins;
  }
 
  if (arguments.length === 1) {
    return this._.mixins[name];
  }
 
  this._.mixins[name] = fn;
  return this;
};
 
/**
 * Assign import `fn` to `name` or return the value of `name`
 * if no other arguments are passed.
 *
 * ```js
 * template.imports('log', function(msg) {
 *   return console.log(msg);
 * });
 * ```
 * @param {String} `name` The name of the import to add.
 * @param {Function} `fn` The actual import function.
 * @api private
 */
 
Template.prototype.imports = function(name, fn) {
  debug.engine('adding [imports]: %s', name);
 
  if (arguments.length === 0) {
    return this._.imports;
  }
 
  if (arguments.length === 1) {
    return this._.imports[name];
  }
 
  this._.imports[name] = fn;
  return this;
};
 
/**
 * Register generic template helpers that are not specific to an
 * engine.
 *
 * Helpers registered using this method will be passed to every
 * engine, so this method is best for generic javascript functions -
 * unless you want to see Lo-Dash blow up from `Handlebars.SafeString`.
 *
 * ```js
 * template.helper('lower', function(str) {
 *   return str.toLowerCase();
 * });
 * ```
 *
 * @param {String} `key` Helper name
 * @param {Function} `fn` Helper function.
 * @api public
 */
 
Template.prototype.helper = function(name, fn) {
  debug.helper('adding helper: %s', name);
  this._.helpers.addHelper(name, fn);
  return this;
};
 
/**
 * Register multiple helpers.
 *
 * ```js
 * template.addHelpers({
 *   a: function() {},
 *   b: function() {},
 *   c: function() {},
 * });
 * ```
 *
 * @param {Object|Array} `helpers` Object, array of objects, or glob patterns.
 * @api public
 */
 
Template.prototype.helpers = function(helpers, options) {
  debug.helper('adding helpers: %s', helpers);
 
  if (typeOf(helpers) === 'object') {
    merge(this._.helpers, helpers);
  } else Eif (Array.isArray(helpers) || typeof helpers === 'string') {
    // sniff tests: if it's an object, it's not a glob
    if (typeOf(helpers[0]) === 'object') {
      _.reduce(helpers, function (acc, o) {
        return merge(acc, o);
      }, this._.helpers);
    } else {
       var files = glob.sync(helpers, options);
      _.reduce(files, function (acc, fp) {
        var name = path.basename(fp, path.extname(fp));
        acc[name] = require(path.resolve(fp));
        return acc;
      }, this._.helpers);
    }
  }
 
  return this;
};
 
/**
 * Register generic async template helpers that are not specific to an
 * engine.
 *
 * As with the sync version, helpers registered using this method will
 * be passed to every engine, so this method is best for generic
 * javascript functions.
 *
 * ```js
 * template.asyncHelper('lower', function(str, next) {
 *   str = str.toLowerCase();
 *   next();
 * });
 * ```
 *
 * @param {String} `name` Helper name.
 * @param {Function} `fn` Helper function
 * @api public
 */
 
Template.prototype.asyncHelper = function(name, fn) {
  debug.helper('adding async helper: %s', name);
  this._.asyncHelpers.addAsyncHelper(name, fn);
  return this;
};
 
/**
 * Register multiple async helpers.
 *
 * ```js
 * template.addAsyncHelpers({
 *   a: function() {},
 *   b: function() {},
 *   c: function() {},
 * });
 * ```
 *
 * @param {Object|Array} `helpers` Object, array of objects, or glob patterns.
 * @api public
 */
 
Template.prototype.asyncHelpers = function(helpers) {
  debug.helper('adding async helpers: %s', helpers);
  var loader = this._.asyncHelpers.addAsyncHelpers;
  return loader.apply(loader, arguments);
};
 
/**
 * Register an object of helpers for the given `ext` (engine).
 *
 * ```js
 * template.helpers(require('handlebars-helpers'));
 * ```
 *
 * @param {String} `ext` The engine to register helpers with.
 * @return {Object} Object of helpers for the specified engine.
 * @api public
 */
 
Template.prototype.engineHelpers = function(ext) {
  debug.helper('helpers for engine: %s', ext);
  return this.getEngine(ext).helpers;
};
 
/**
 * Create helpers for each default template `type`.
 *
 * @param {String} `type` The type of template.
 * @param {String} `plural` Plural form of `type`.
 * @api private
 */
 
Template.prototype.defaultHelper = function(subtype, plural) {
  debug.helper('default helper: %s', subtype);
  var self = this;
 
  this.helper(subtype, function (key, locals) {
    debug.helper('helper: [%s / %s]', subtype, key);
    var partial = self.views[plural][key];
 
    if (!partial) {
      // TODO: use actual delimiters in messages
      debug.err(chalk.red('helper {{' + subtype + ' "' + key + '"}} not found.'));
      return '';
    }
 
    var locs = merge({}, this.context, locals);
 
    var content = self.renderTemplate(partial, locs);
    if (content instanceof Error) {
      throw content;
    }
    return content;
  });
};
 
/**
 * Create async helpers for each default template `type`.
 *
 * @param {String} `type` The type of template.
 * @param {String} `plural` Plural form of `type`.
 * @api private
 */
 
Template.prototype.defaultAsyncHelper = function(subtype, plural) {
  debug.helper('default async helper: %s', subtype);
  var self = this;
 
  this.asyncHelper(subtype, function (key, locals, next) {
    debug.helper('async helper: [%s / %s]', subtype, key);
 
    var last = arguments[arguments.length - 1];
    if (typeof locals === 'function') {
      next = locals;
      locals = {};
    }
 
    if (typeof next !== 'function') {
      next = last;
    }
 
    var partial = self.views[plural][key];
 
    if (!partial) {
      // TODO: use actual delimiters in messages
      debug.err(chalk.red('helper {{' + subtype + ' "' + key + '"}} not found.'));
      return next(null, '');
    }
 
    var locs = merge({}, this.context, locals);
    var render = self.renderSubtype(subtype);
 
    render(key, locs, function (err, content) {
      if (err) return next(err);
      next(null, content);
      return;
    });
  });
};
 
/**
 * Define a custom loader for loading templates.
 *
 * @param  {String} `plural`
 * @param  {Object} `options`
 * @param  {Array} `fns`
 * @param  {Function} `done`
 */
 
Template.prototype.loader = function (plural, options, stack, done) {
  debug.loader('loader: %j', arguments);
  var self = this;
 
  Eif (arguments.length !== 1) {
    done = done || function () {};
    stack = stack || [];
 
    self.loaders[plural] = function (/*key, value, fns, callback*/) {
      var args = slice(arguments);
      var first;
 
      if (Array.isArray(args[0])) {
        first = args.shift();
      }
 
      var fns = arr.first(args, 'array') || [];
      var callback = arr.first(args, 'function');
 
      Iif (typeof callback !== 'function') {
        throw new Error('Template#loader() expects `callback` to be a function.');
      }
 
      // remove the arrays and functions from args
      args = arr.filter(args, function (ele) {
        return !Array.isArray(ele) && typeof ele !== 'function';
      });
 
      if (first != null) {
        args.unshift(first);
      }
 
      // find our stack to call
      var loaders = stack.concat(fns);
 
      // pass the loaders through the waterfall to get the templates
      var firstFn = loaders[0];
 
      loaders[0] = function (next) {
        args.push(next);
        return firstFn.apply(self, args);
      };
 
      loaders = utils.bindAll(loaders, self);
 
      return utils.runLoaderStack(loaders, function (err, template) {
        return callback(err, done(err, template) || template);
      });
 
    };
  }
  return self.loaders[plural];
};
 
/**
 * Default load function used for loading templates.
 *
 * @param  {String} `plural`
 * @param  {Object} `options`
 * @param  {Array} `fns` Loader functions.
 * @param  {Function} `done`
 */
 
Template.prototype.load = function(subtype, plural, options, fns, done) {
  debug.loader('loading: %j', arguments);
  var self = this;
 
  // If the loader stack is empty, fallback to defaults
  if (fns == null || fns.length === 0) {
    fns = this.defaultLoader(plural, options);
  }
 
  var opts = extend({}, options);
 
  function getLoader() {
    if (opts.loadFn) {
      var callback = arguments[arguments.length - 1];
      var args = slice(arguments, 0, arguments.length - 1);
 
      callback(null, opts.loadFn.apply(self, args));
    } else {
      self.loader(plural, opts, fns, done).apply(self, arguments);
    }
  }
 
  return function (/*key, value, fns*/) {
    debug.loader('loading template: %j', arguments);
    var args = slice(arguments);
    var last = args[args.length - 1];
    var cb = function () {};
 
    if (typeof last === 'function') {
      cb = args.pop();
    }
 
    args = args.concat([function (err, template) {
      if (err) return cb(err);
 
      // validate the template object before moving on
      self.validate(template);
 
      // Add a render method to the template
      // TODO: allow additional opts to be passed
      forOwn(template, function (value) {
        // this engine logic is temporary until we decide
        // how we want to allow users to control this.
        // for now, this allows the user to change the engine
        // preference in the the `getExt()` method.
        value.options = value.options || {};
        if (hasOwn(opts, 'engine')) {
          var ext = opts.engine;
          if (ext[0] !== '.') {
            ext = '.' + ext;
          }
          value.options._engine = ext;
        }
        if (hasOwn(opts, 'delims')) {
          value.options.delims = opts.delims;
        }
 
        value.render = function (locals, cb) {
          return self.renderTemplate(this, locals, cb);
        };
      });
 
      // Run middleware
      self.dispatch(template);
 
      // Add template to the cache
      extend(self.views[plural], template);
      cb(null);
    }]);
 
    getLoader.apply(self, args);
    return self;
  };
};
 
/**
 * Validate a template object to ensure that it has the properties
 * expected for applying layouts, choosing engines, and so on.
 *
 * @param  {String} `key` Template key
 * @param  {Object} `value` Template object
 * @api public
 */
 
Template.prototype.validate = function(template) {
  if (template == null || typeOf(template) !== 'object') {
    debug.err('`template` must be an object.');
  }
 
  forOwn(template, function (value, key) {
    Iif (key == null || typeof key !== 'string') {
      debug.err('template `key` must be a string.');
    }
 
    if (value == null || typeOf(value) !== 'object') {
      debug.err('template `value` must be an object.');
    }
 
    if (!hasOwn(value, 'path')) {
      debug.err('template `value` must have a `path` property.');
    }
 
    if (!hasOwn(value, 'content')) {
      debug.err('template `value` must have a `content` property.');
    }
  });
};
 
/**
 * Normalize a template object to ensure it has the necessary
 * properties to be rendered by the current renderer.
 *
 * @param  {Object} `template` The template object to normalize.
 * @param  {Object} `options` Options to pass to the renderer.
 *     @option {Function} `renameKey` Override the default function for renaming
 *             the key of normalized template objects.
 * @return {Object} Normalized template.
 * @api private
 */
 
Template.prototype.normalize = function(plural, template, options) {
  debug.template('normalizing: [%s]: %j', plural, template);
  this.lazyrouter();
 
  if (this.option('normalize')) {
    return this.options.normalize.apply(this, arguments);
  }
 
  forOwn(template, function (value, key) {
    value.options = extend({ subtype: plural }, options, value.options);
    var ext = this.getExt(value, options);
 
    value.layout = value.layout || value.locals.layout;
    template[key] = value;
  }, this);
  return template;
};
 
/**
 * Get the given `collection` from views. Optionally
 * pass a `name` to get a specific template from the
 * collection.
 *
 * @param {String} `collection`
 * @param {String} `name`
 * @return {Object}
 * @api public
 */
 
Template.prototype.view = function(collection, name) {
  if (this.views.hasOwnProperty(collection)) {
    var obj = this.views[collection];
    if (!name) {
      return obj;
    }
    return obj[name];
  }
  return null;
};
 
/**
 * Private method for tracking the `subtypes` created for each
 * template collection type, to make it easier to get/set templates
 * and pass them properly to registered engines.
 *
 * @param {String} `plural` e.g. `pages`
 * @param {Object} `options`
 * @api private
 */
 
Template.prototype.setType = function(subtype, plural, options) {
  debug.template('setting subtype: %s', subtype);
  var opts = extend({}, options);
 
  // Make an association between `subtype` and its `plural`
  this.collection[subtype] = plural;
 
  if (opts.isRenderable) {
    this.type.renderable.push(plural);
  }
 
  if (opts.isLayout) {
    this.type.layout.push(plural);
  }
 
  if (opts.isPartial || (!opts.isRenderable && !opts.isLayout)) {
    this.type.partial.push(plural);
    opts.isPartial = true;
  }
  return opts;
};
 
/**
 * Get all views of the given [type]. Valid values are
 * `renderable`, `layout` or `partial`.
 *
 * ```js
 * var pages = template.getType('renderable');
 * //=> { pages: { 'home.hbs': { ... }, 'about.hbs': { ... }}, posts: { ... }}
 * ```
 *
 * [type]: ./template-types
 *
 * @param {String} `type`
 * @param {Object} `opts`
 * @api public
 */
 
Template.prototype.getType = function(type) {
  debug.template('getting type: %s', type);
  var arr = this.type[type];
 
  return arr.reduce(function(acc, plural) {
    acc[plural] = this.views[plural];
    return acc;
  }.bind(this), {});
};
 
/**
 * Merge all collections of the given `type` into a single
 * collection. e.g. `partials` and `includes` would be merged.
 *
 * If an array of `collections` is passed, only those collections
 * will be merged and the order in which the collections are defined
 * in the array will be respected.
 *
 * @param {String} `type` The template type to search.
 * @param {String} `collections` Optionally pass an array of collections
 * @api public
 */
 
Template.prototype.mergeType = function(type, collections) {
  debug.template('merging [type]: %s', type);
  var obj = this.getType(type);
 
  collections = arrayify(collections || Object.keys(obj));
  var len = collections.length;
  var o = {};
  var i = len - 1;
 
  while (len--) {
    var colection = collections[i--];
    for (var key in this.views[colection]) {
      Eif (this.views[colection].hasOwnProperty(key)) {
        o[key] = this.views[colection][key];
      }
    }
  }
  return o;
};
 
/**
 * Merge all `layout` collections based on user-defined options.
 *
 * ```js
 *
 *
 * @param {String} `type` The template type to search.
 * @param {String} `collections` Optionally pass an array of collections
 * @api public
 */
 
Template.prototype.mergeLayouts = function(options) {
  debug.template('merging layouts: %j', options);
 
  var layouts = {};
  var mergeLayouts = this.option('mergeLayouts');
 
  if (typeof mergeLayouts === 'function') {
    return mergeLayouts.call(this, arguments);
  }
 
  if (Array.isArray(mergeLayouts)) {
    layouts = this.mergeType('layout', mergeLayouts);
  } else if (mergeLayouts === false) {
    layouts = this.views.layouts;
  } else {
    layouts = this.mergeType('layout');
  }
  forOwn(layouts, function (value, key) {
    this.mergeTypeContext('layouts', key, value.locals, value.data);
  }, this);
  return layouts;
};
 
/**
 * Default method for determining how partials are to be passed to
 * engines. By default, all `partial` collections are merged onto a
 * single `partials` object. To keep each collection on a separate
 * object, you can do `template.disable('mergePartials')`.
 *
 * If you want to control how partials are merged, you can also
 * pass a function to the `mergePartials` option:
 *
 * ```js
 * template.option('mergePartials', function(locals) {
 *   // do stuff
 * });
 * ```
 *
 * @param  {Object} `locals`
 * @return {Object}
 * @api public
 */
 
Template.prototype.mergePartials = function(locals) {
  debug.template('merging partials [%s]: %j', arguments);
 
  var mergePartials = this.option('mergePartials');
  if (typeof mergePartials === 'function') {
    return mergePartials.call(this, locals);
  }
 
  var opts = {};
  opts.partials = _.cloneDeep(locals.partials || {});
 
  // loop over each `partial` collection
  this.type.partial.forEach(function (plural) {
    var collection = this.views[plural];
 
    // Loop over the templates in the collection
    forOwn(collection, function (value, key/*, template*/) {
      this.mergeTypeContext('partials', key, value.locals, value.data);
      value.content = this.applyLayout(value, this.cache._context.partials[key]);
 
      // If `mergePartials` is true combine all `partial` subtypes
      if (mergePartials === true) {
        opts.partials[key] = value.content;
 
      // Otherwise, each partial subtype on a separate object
      } else {
        opts[plural] = opts[plural] || {};
        opts[plural][key] = value.content;
      }
    }, this);
  }, this);
 
  locals.options = extend({}, locals.options, opts);
  return locals;
};
 
/**
 * Search all `subtype` objects of the given `type`, returning
 * the first template found with the given `key`. Optionally pass
 * an array of `subtypes` to limit the search;
 *
 * @param {String} `type` The template type to search.
 * @param {String} `key` The template to find.
 * @param {Array} `subtypes`
 * @api private
 */
 
Template.prototype.find = function(type, key, subtypes) {
  var o = this.mergeType(type, subtypes);
 
  if (o && typeOf(o) === 'object' && hasOwn(o, key)) {
    return o[key];
  }
 
  if (this.enabled('strict errors')) {
    throw new Error('Cannot find ' + type + ' template: "' + key + '"');
  }
};
 
/**
 * Search all renderable `subtypes`, returning the first template
 * with the given `key`.
 *
 *   - If `key` is not found an error is thrown.
 *   - Optionally limit the search to the specified `subtypes`.
 *
 * @param {String} `key` The template to search for.
 * @param {Array} `subtypes`
 * @api public
 */
 
Template.prototype.findRenderable = function(key, subtypes) {
  return this.find('renderable', key, subtypes);
};
 
/**
 * Search all layout `subtypes`, returning the first template
 * with the given `key`.
 *
 *   - If `key` is not found an error is thrown.
 *   - Optionally limit the search to the specified `subtypes`.
 *
 * @param {String} `key` The template to search for.
 * @param {Array} `subtypes`
 * @api public
 */
 
Template.prototype.findLayout = function(key, subtypes) {
  return this.find('layout', key, subtypes);
};
 
/**
 * Search all partial `subtypes`, returning the first template
 * with the given `key`.
 *
 *   - If `key` is not found an error is thrown.
 *   - Optionally limit the search to the specified `subtypes`.
 *
 * @param {String} `key` The template to search for.
 * @param {Array} `subtypes`
 * @api public
 */
 
Template.prototype.findPartial = function(key, subtypes) {
  return this.find('partial', key, subtypes);
};
 
/**
 * Convenience method for finding a template by `name` on
 * the given collection. Optionally specify a file extension.
 *
 * @param {String} `plural` The view collection to search.
 * @param {String} `name` The name of the template.
 * @param {String} `ext` Optionally pass a file extension to append to `name`
 * @api public
 */
 
Template.prototype.lookup = function(plural, name, ext) {
  var views = this.views[plural];
 
  if (hasOwn(views, name)) {
    return views[name];
  }
 
  if (hasOwn(views, name + (ext || '.md'))) {
    return views[name + (ext || '.md')];
  }
 
  if (this.enabled('strict errors')) {
    throw new Error('Cannot find ' + plural + ': "' + name + '"');
  }
 
  debug.err('Cannot find ' + plural + ': "' + name + '"');
  return null;
};
 
/**
 * Create a new `view` collection and associated convience methods.
 *
 * Note that when you only specify a name for the type, a plural form is created
 * automatically (e.g. `page` and `pages`). However, you can define the
 * `plural` form explicitly if necessary.
 *
 * @param {String} `subtype` Singular name of the collection to create, e.g. `page`.
 * @param {String} `plural` Plural name of the collection, e.g. `pages`.
 * @param {Object} `options` Options for the collection.
 *   @option {Boolean} [options] `isRenderable` Templates that may be rendered at some point
 *   @option {Boolean} [options] `isLayout` Templates to be used as layouts
 *   @option {Boolean} [options] `isPartial` Templates to be used as partial views or includes
 * @param {Function|Array} `fns` Middleware function or functions to be run for every template of this type.
 * @return {Object} `Template` to enable chaining.
 * @api public
 */
 
Template.prototype.create = function(subtype, plural/*, options, fns, done*/) {
  var args = slice(arguments);
 
  /**
   * Normalize args to make them more predictable for loaders
   */
 
  if (typeof plural !== 'string') {
    var name = subtype;
    args[0] = plural = (name + 's');
    args.unshift(name);
  }
 
  if (typeOf(args[2]) !== 'object') {
    args = slice(args, 0, 2).concat([{}]).concat(slice(args, 2));
  }
 
  if (!Array.isArray(args[3])) {
    args = slice(args, 0, 3).concat([[]]).concat(slice(args, 3));
  }
 
  debug.template('creating subtype: [%s / %s]', subtype, plural);
 
  this.views[plural] = this.views[plural] || {};
  args[2] = this.setType(subtype, plural, args[2]);
 
  // Add convenience methods for this sub-type
  this.decorate.apply(this, args);
 
  /**
   * Create helper functions
   */
 
  var opts = args[2] || {};
 
  if (this.enabled('default helpers') && opts.isPartial && !opts.disableHelpers) {
    // Create a sync helper for this type
    Eif (!hasOwn(this._.helpers, subtype)) {
      this.defaultHelper(subtype, plural);
    }
 
    // Create an async helper for this type
    Eif (!hasOwn(this._.asyncHelpers, subtype)) {
      this.defaultAsyncHelper(subtype, plural);
    }
  }
  return this;
};
 
/**
 * Decorate a new template subtype with convenience methods.
 *
 * @param  {String} `subtype`
 * @param  {String} `plural`
 * @param  {Object} `options`
 * @api private
 */
 
Template.prototype.decorate = function(subtype, plural/*, options, fns, done*/) {
  debug.template('decorating subtype: [%s / %s]', subtype, plural);
 
  /**
   * Ininiatlize the loader to be used. If `fns` is empty,
   * we fallback to the default loader stack.
   */
 
  var load = this.load.apply(this, arguments);
 
  /**
   * Add a method to `Template` for `plural`
   */
 
  mixin(plural, function (/*key, value, fns*/) {
    return load.apply(this, arguments);
  });
 
  /**
   * Add a method to `Template` for `subtype`
   */
 
  mixin(subtype, function (/*key, value, locals, opts*/) {
    return this[plural].apply(this, arguments);
  });
 
  /**
   * Add a `get` method to `Template` for `subtype`
   */
 
  mixin(methodName('get', subtype), function (key) {
    return this.views[plural][key];
  });
 
  /**
   * Add a `render` method to `Template` for `subtype`
   */
 
  mixin(methodName('render', subtype), function () {
    return this.renderSubtype(subtype);
  });
};
 
/**
 * Base compile method. Use `engine` to compile `content` with the
 * given `options`
 *
 * @param  {Object} `engine` Engine object, with `.compile()` method
 * @param  {Object} `content` The content string to compile.
 * @param  {Object} `options` options to pass to registered view engines.
 * @return {Function} The compiled template string.
 * @api private
 */
 
Template.prototype.compileBase = function(engine, content, options) {
  debug.render('compileBase: %j', arguments);
  if (!hasOwn(engine, 'compile')) {
    throw new Error('`.compile()` method not found on: "' + engine.name + '".');
  }
  try {
    return engine.compile(content, options);
  } catch (err) {
    debug.err('compile: %j', err);
    return err;
  }
};
 
/**
 * Compile content on the given `template` object with the specified
 * engine `options`.
 *
 * @param  {Object} `template` The template object with content to compile.
 * @param  {Object} `options` Options to pass along to the engine when compile. May include a `context` property to bind to helpers.
 * @return {Object} Template object to enable chaining.
 * @api public
 */
 
Template.prototype.compileTemplate = function(template, options, async) {
  var self = this;
  debug.render('compileTemplate: %j', template);
 
  if (typeOf(template) !== 'object') {
    throw new Error('Template#compileTemplate() expects an object, got: "'
      + typeOf(template) + ' / '+ template + '".');
  }
 
  // reference to options in case helpers are needed later
  var opts = options || {};
  var context = opts.context || {};
  delete opts.context;
 
  template.options = template.options || {};
  template.options.layout = template.layout;
 
  // find ext and engine to use
  var ext = this.getExt(template, context);
  var engine = this.getEngine(ext);
 
  // Handle custom template delimiters and escaping
  this.handleDelims(ext, engine, template, opts);
 
  // additional delim settings
  var settings = this.getDelims(ext);
  if (settings) {
    extend(opts, settings);
  }
 
  // Bind context to helpers before passing to the engine.
  this.bindHelpers(opts, context, async);
  opts.debugEngine = this.option('debugEngine');
 
  // if a layout is defined, apply it before compiling
  var content = template.content;
  content = this.applyLayout(template, extend({}, context, opts));
 
  // compile template
  return this.compileBase(engine, content, opts);
};
 
/**
 * Compile `content` with the given `options`.
 *
 * @param  {Object|String} `file` String or normalized template object.
 * @param  {Object} `options`
 * @param  {Boolean} `async` Load async helpers
 * @return {Function} Compiled function.
 * @api public
 */
 
Template.prototype.compile = function(content, options, async) {
  debug.render('compile: %j', arguments);
 
  if (content == null) {
    throw new Error('Template#compile() expects a string or object.');
  }
 
  if (typeOf(content) === 'object') {
    return this.compileTemplate(content, options, async);
  }
 
  var template = this.findRenderable(content);
  if (typeOf(template) === 'object') {
    return this.compileTemplate(template, options, async);
  }
 
  return this.compileString(content, options, async);
};
 
/**
 * Compile the given string with the specified `options`.
 *
 * The primary purpose of this method is to get the engine before
 * passing args to `.compileBase()`.
 *
 * @param  {String} `str` The string to compile.
 * @param  {Object} `options` Options to pass to registered view engines.
 * @param  {Boolean} `async` Load async helpers
 * @return {Function}
 * @api public
 */
 
Template.prototype.compileString = function(str, options, async) {
  debug.render('render string: %s', str);
  if (typeof options === 'boolean') {
    async = options;
    options = {};
  }
 
  options = extend({locals: {}}, options);
  var locals = options.locals;
 
  var template = { content: str, locals: locals, options: options };
  return this.compileTemplate(template, options, async);
};
 
/**
 * Base render method. Use `engine` to render `content` with the
 * given `options` and `callback`.
 *
 * @param  {Object} `engine` Engine object, with `.render()` and/or `.renderSync()` method(s)
 * @param  {Object} `content` The content string to render.
 * @param  {Object} `options` Locals and/or options to pass to registered view engines.
 * @param  {Function} `cb` If a callback is passed, `.render()` is used, otherwise `.renderSync()` is used.
 * @return {String} The rendered template string.
 * @api private
 */
 
Template.prototype.renderBase = function(engine, content, options, cb) {
  debug.render('renderBase: %j', arguments);
  if (typeof options === 'function') {
    cb = options;
    options = {};
  }
 
  if (typeof cb !== 'function') {
    return this.renderSync(engine, content, options);
  }
 
  return this.renderAsync(engine, content, options, cb);
};
 
/**
 * Render content on the given `template` object with the specified
 * engine `options` and `callback`.
 *
 * @param  {Object} `template` The template object with content to render.
 * @param  {Object} `locals` Locals and/or options to pass to registered view engines.
 * @return {String}
 * @api public
 */
 
Template.prototype.renderTemplate = function(template, locals, cb) {
  var self = this;
  debug.render('renderTemplate: %j', template);
  if (typeof locals === 'function') {
    cb = locals;
    locals = {};
  }
  if (typeOf(template) !== 'object') {
    throw new Error('Template#renderTemplate() expects an object, got: "'
      + typeOf(template) + ' / '+ template + '".');
  }
 
  template.options = template.options || {};
  template.options.layout = template.layout;
 
  // find any options passed in on locals
  locals = locals || {};
  var opts = extend({}, locals.options);
 
  // Merge `.render()` locals with template locals
  locals = this.mergeContext(template, locals);
  extend(opts, locals.options);
 
  // find the engine to use to render
  var ext = this.getExt(template, opts);
  var engine = this.getEngine(ext);
 
  // handle pre-render middleware routes
  this.handle('before', template, handleError(template, 'before'));
 
  // compile the template if it hasn't been already
  if (!template.fn) {
    opts.context = opts.context || locals;
    opts.delims = opts.delims || opts.context.delims;
    opts.layoutDelims = opts.layoutDelims || opts.context.layoutDelims;
    template.fn = this.compileTemplate(template, opts, typeof cb === 'function');
  }
 
  var cloned = _.cloneDeep(template);
  var content = template.fn;
 
  // backwards compatibility for engines that don't support compile
  if (typeof content === 'string') {
    locals = extend(locals, opts);
  }
 
  /**
   * sync
   */
 
  // when a callback is not passed, render and handle middleware
  if (typeof cb !== 'function') {
    cloned.content = this.renderBase(engine, content, locals, cb);
 
    // handle post-render middleware routes
    this.handle('after', cloned, handleError(template, 'after'));
    return cloned.content;
  }
 
  /**
   * async
   */
 
  // when a callback is passed, render and handle middleware in callback
  return this.renderBase(engine, content, locals, function (err, content) {
    if (err) return cb.call(self, err);
    cloned.content = content;
    self.handle('after', cloned, handleError(template, 'after'));
    return cb.call(self, null, cloned.content);
  });
};
 
/**
 * Base sync render method. Uses the given `engine` to render
 * `content` with the given `options`.
 *
 * @param  {Object} `engine` Engine object must have a `.renderSync()` method.
 * @param  {Object} `content` The content string to render.
 * @param  {Object} `options` Locals and/or options to pass to registered view engines.
 * @return {String} The rendered template string.
 * @api private
 */
 
Template.prototype.renderSync = function(engine, content, options) {
  if (!hasOwn(engine, 'renderSync')) {
    throw new Error('`.renderSync()` method not found on: "' + engine.name + '".');
  }
  try {
    return engine.renderSync(content, options);
  } catch (err) {
    debug.err('renderSync: %j', err);
    return err;
  }
};
 
/**
 * Base async render method. Uses the given `engine` to render
 * `content` with the given `options` and `callback`.
 *
 * @param  {Object} `engine` Engine object, with `.render()` and/or `.renderSync()` method(s)
 * @param  {Object} `content` The content string to render.
 * @param  {Object} `options` Locals and/or options to pass to registered view engines.
 * @param  {Function} `cb` If a callback is passed, `.render()` is used, otherwise `.renderSync()` is used.
 * @return {String} The rendered template string.
 * @api private
 */
 
Template.prototype.renderAsync = function(engine, content, options, cb) {
  if (!hasOwn(engine, 'render')) {
    throw new Error('`.render()` method not found on: "' + engine.name + '".');
  }
 
  try {
    var self = this;
    engine.render(content, options, function (err, res) {
      if (err) {
        debug.render('renderAsync: %j', err);
        cb.call(self, err);
        return;
      }
 
      self._.asyncHelpers.resolve(res, function (err, res) {
        if (err) {
          debug.err('renderAsync [helpers]: %j', err);
          return cb.call(self, err);
        }
 
        cb.call(self, null, res);
      });
    });
  } catch (err) {
    debug.err('renderAsync [catch]: %j', err);
    cb.call(self, err);
  }
};
 
/**
 * Render `content` with the given `options` and optional `callback`.
 *
 * @param  {Object|String} `file` String or normalized template object.
 * @param  {Object} `locals` Locals and/or options to pass to registered view engines.
 * @return {String} Rendered string.
 * @api public
 */
 
Template.prototype.render = function(content, locals, cb) {
  debug.render('render: %j', arguments);
 
  if (content == null) {
    throw new Error('Template#render() expects a string or object.');
  }
 
  if (typeOf(content) === 'object') {
    return this.renderTemplate(content, locals, cb);
  }
 
  var template = this.findRenderable(content);
  if (typeOf(template) === 'object') {
    return this.renderTemplate(template, locals, cb);
  }
 
  return this.renderString(content, locals, cb);
};
 
/**
 * Render the given string with the specified `locals` and `callback`.
 *
 * The primary purpose of this method is to get the engine before
 * passing args to `.renderBase()`.
 *
 * @param  {String} `str` The string to render.
 * @param  {Object} `locals` Locals and/or options to pass to registered view engines.
 * @return {String}
 * @api public
 */
 
Template.prototype.renderString = function(str, locals, cb) {
  debug.render('render string: %s', str);
  if (typeof locals === 'function') {
    cb = locals;
    locals = {};
  }
 
  locals = extend({options: {}}, locals);
  var options = locals.options;
 
  var template = { content: str, locals: locals, options: options };
  return this.renderTemplate(template, locals, cb);
};
 
/**
 * Returns a render function for rendering templates of the given `subtype`.
 *
 * Mostly used internally as a private method, but it's exposed as a
 * public method since there are cases when it might be useful, like
 * for rendering templates in a gulp/grunt/assemble plugin.
 *
 * @param  {String} `plural` Template subtype, e.g. `pages`
 * @return {Function} `params`
 *   @param  {String} [params] `str` The string to render.
 *   @param  {Object} [params] `locals` Locals and/or options to pass to registered view engines.
 *   @return {String} [params] `string` The rendered string.
 * @api public
 */
 
Template.prototype.renderSubtype = function(subtype) {
  debug.render('render subtype: [%s / %s]', subtype);
 
  // get the plural name of the given subtype
  var plural = this.collection[subtype];
  var self = this;
 
  return function (key, locals, cb) {
    debug.render('rendering subtype: %j', arguments);
    if (typeof locals === 'function') {
      cb = locals;
      locals = {};
    }
 
    // Return the first matching template from a `renderable` subtype
    var template = self.lookup(plural, key);
    if (template == null) {
      throw new Error('Template#renderSubtype() Cannot find template: "' + key + '".');
    }
    return self.renderTemplate(template, locals, cb);
  };
};
 
/**
 * Render the given string with the specified `locals` and `callback`.
 *
 * @param  {String} `str` The string to render.
 * @param  {Object} `locals` Locals and/or options to pass to registered view engines.
 * @return {String}
 * @api public
 */
 
Template.prototype.renderType = function(type, subtype) {
  debug.render('render type: [%s / %s]', type, subtype);
  var self = this;
 
  return function (key, locals, cb) {
    debug.render('rendering type: %j', arguments);
    if (typeof locals === 'function') {
      cb = locals;
      locals = {};
    }
 
    var template = self.find(type, key, subtype);
    if (template == null) {
      throw new Error('Template#renderType() Cannot find template: "' + key + '".');
    }
    return self.renderTemplate(template, locals, cb);
  };
};
 
/**
 * Expose the current context as `this` in helpers.
 *
 *   - Exposes `locals` on the `context` property
 *   - Exposes `Template` on the `app` property
 *
 * @param  {Object} `options` Additional options that may contain helpers
 * @param  {Object} `context` Used as the context to bind to helpers
 * @param  {Boolean} `async` Is the helper async?
 * @return {Object}
 */
 
Template.prototype.bindHelpers = function (options, context, async) {
  debug.helper('binding helpers: %j %j', context, options);
 
  var helpers = _.cloneDeep(this.options.helpers || {});
  extend(helpers, _.cloneDeep(this._.helpers));
  extend(helpers, _.cloneDeep(this._.imports));
 
  if (async) {
    helpers = extend({}, helpers, this._.asyncHelpers);
  }
  extend(helpers, _.cloneDeep(options.helpers || {}));
 
  var o = {};
  o.context = context || {};
  o.app = this;
 
  options.helpers = utils.bindAll(helpers, o);
};
 
/**
 * Build the context to be passed to templates. This can be
 * overridden by passing a function to the `mergeContext`
 * option.
 *
 * ```js
 * template.option('mergeContext', function(template, locals) {
 *   return _.merge(template.data, template.locals, locals);
 * });
 * ```
 *
 * @param  {Object} `template` Template object
 * @param  {Object} `locals`
 * @return {Object} The object to be passed to engines/templates as context.
 */
 
Template.prototype.mergeContext = function(template, locals) {
  if (typeof this.option('mergeContext') === 'function') {
    return this.option('mergeContext').apply(this, arguments);
  }
 
  var context = {};
  merge(context, this.cache.data);
 
  // control the order in which `locals` and `data` are merged
  if (this.enabled('preferLocals')) {
    merge(context, template.data);
    merge(context, template.locals);
  } else {
    merge(context, template.locals);
    merge(context, template.data);
  }
 
  // Merge in partials to pass to engines
  merge(context, this.mergePartials(context));
 
  // Merge in `locals/data` from templates
  merge(context, this.cache._context.partials);
  merge(context.layouts || {}, this.cache.layouts);
  merge(context, locals);
  return context;
};
 
/**
 * Build the context for a specific template and type.
 *
 * ```js
 * template.mergeTypeContext('partials', 'sidenav', locals, data);
 * ```
 *
 * @param  {String} `type` Template type to merge
 * @param  {String} `key` Key of template to use
 * @param  {Object} `locals` Locals object from template
 * @param  {Object} `data` Data object from template
 * @api private
 */
 
Template.prototype.mergeTypeContext = function(type, key, locals, data) {
  this.cache._context[type] = this.cache._context[type] || {};
  this.cache._context[type][key] = extend({}, locals, data);
};
 
/**
 * Middleware error handler
 *
 * @param {Object} `template`
 * @param {String} `method` name
 * @api private
 */
 
function handleError(template, method) {
  return function (err) {
    if (err) {
      console.log(chalk.red('Error running ' + method + ' middleware for', template.path));
      console.log(chalk.red(err));
    }
  };
}
 
/**
 * Create a camel-cased method name for the given
 * `method` and `type`.
 *
 *     'get' + 'page' => `getPage`
 *
 * @param  {String} `type`
 * @param  {String} `name`
 * @return {String}
 */
 
function methodName(method, type) {
  return camelize(method)
    + type[0].toUpperCase()
    + type.slice(1);
}
 
/**
 * Extend the `Template` prototype with a new method.
 *
 * @param  {String} `method` The method name.
 * @param  {Function} `fn`
 * @api private
 */
 
function mixin(method, fn) {
  Template.prototype[method] = fn;
}
 
/**
 * Utility method to define getters.
 *
 * @param  {Object} `o`
 * @param  {String} `name`
 * @param  {Function} `getter`
 * @return {Getter}
 * @api private
 */
 
function defineGetter(o, name, getter) {
  Object.defineProperty(o, name, {
    configurable: false,
    enumerable: false,
    get: getter,
    set: function() {}
  });
}