3

Here is a boiled-down version of what I'm trying to accomplish:

mixin foo(bar)
    = bar + ".html"

a(href= +foo("baz")) test

I'd like to have the anchor tag be compiled as <a href="baz.html">test</a>, but what I'm getting instead are type errors, on foo not being a function. Although I do see that it technically isn't a function, is this not a scenario where a mixin would be useful? I've searched the pug documentation for use-case scenarios similar to mine, but without success.

Is what I'm trying to achieve here possible with mixins? Or is this only possible with regular JS functions passed as context variables?

gandreadis
  • 3,004
  • 2
  • 26
  • 38

2 Answers2

6

I think you want to use unbuffered Javascript for this. For your use case, the code would be like so.

-
    function foo(bar) {
        return bar + ".html";
    }

a(href=foo("baz")) test

This would result in the following HTML:

<a href="baz.html">test</a>

Explanation

Unbuffered Javascript is template logic which will not be emitted in the final result. Unbuffered Javascript is annotated by a dash (-). Multi line unbuffered Javascript is defined by a dash with a single tab indent.

Single line

-var foo = "bar"; 

Multi line

-
    function randomNumber() {
        return 4;
    }

Documentation: https://pugjs.org/language/code.html

DevNebulae
  • 4,566
  • 3
  • 16
  • 27
  • Thanks! That's what I had tried initially, as well, but WebStorm threw syntax errors on any blocks of unbuffered code longer than one line having curly brackets. Now I see that this is actually valid syntax, that the pug compiler accepts just fine. It most likely is an issue in the Jetbrains plugin (similar to this [issue](https://youtrack.jetbrains.com/issue/WEB-16966) that was submitted to their issue tracker). – gandreadis Jan 05 '17 at 15:04
0

Just passing along an example using mixins:

Definition

mixin aLink(href, name)
    a(href=href)&attributes(attributes)= name

Usage

+aLink('https://stackoverflow.com/', 'Stack Overflow')(class='text-orange')
iorem
  • 1
  • 2