9

I have the following link:

<a class="btn btn-primary" href="#">View details »</a>

How can I render the link with sitecore glass that it still keeps the css class? With the field renderer in sitecore you used to be able to pass the class along as additional parameters, how does this work with glass?

This is what I have so far:

@RenderLink(x => x.Link)

This only renders the link without the class though.

Any help appreciated. Thx.

5earch
  • 289
  • 2
  • 4
  • 15

3 Answers3

21

You can also make a PageEditor enabled version like this and it should automatically take the Class attribute into account:

@Editable(Model, x => x.Link)

Or when you use RenderLink, you can pass a collection with the class attribute:

@RenderLink(x => x.Link, new System.Collections.Specialized.NameValueCollection { { "class", "btn btn-primary" } })

EDIT: Modified example to working code and added formatting example for Editable

You can specify a format for Editable:

@(Editable<YourModelType>(Model, x => x.Link, string.Format("<a href=\"{0}\" class=\"btn btn-primary\">{1}</a>", x.Link.Url, x.Link.Text)))
Ben Sewards
  • 2,571
  • 2
  • 25
  • 43
Ruud van Falier
  • 8,765
  • 5
  • 30
  • 59
  • Hi Ruud, thanks for your reply: this seems to work: @(RenderLink(x => x.Link, new System.Collections.Specialized.NameValueCollection { { "class", "btn btn-primary" } }, isEditable: true)), how would I pass the class in your first example? – 5earch Oct 25 '13 at 12:46
  • Added another example for Editable – Ruud van Falier Oct 25 '13 at 13:32
  • @RuudvanFalier - This doesn't seem to work with BeginRenderLink - it says class cannot be used as an assignment or target. Also, I don't have orange trousers, is this a problem? – PeterG Jun 12 '14 at 13:31
  • @PeterG - Sounds to me like you have a typo. Also, it will not work without orange trousers, obviously.. – Ruud van Falier Jun 19 '14 at 09:37
  • note: passing an NVC object with class name doesn't work with @Editable(..). – Ben Sewards Oct 28 '15 at 18:54
  • Is it work in PE? First doesn't add class. Second throw exception. – Anton Aug 03 '16 at 19:31
8

@Editable(x => x.Link, new { @class = "btn btn-primary" })

MaksymD
  • 314
  • 1
  • 4
  • 16
1

I have written a helper class using a Fluent API to allow you to add HTML attributes to glass helpers easily.

See blog here: http://mikerobbins.co.uk/2015/07/29/sitecore-razor-glass-attribute-helper-methods-fluent-api/

You can use the helper like this:

@Editable(x => x.Link,new HtmlAttributes().CssClass("Link").Render())
Komainu85
  • 964
  • 6
  • 22