Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing script src dynamically via wicket

Tags:

wicket

I want my page to load javascript dynamically to my body:

<script type= "text/javascript" src="this path should be decided from wicket dynamically"/>

I am using wicket version 1.4 therefore JavaScriptResourceReference does not exist in my version (for my inspection it wasn't ' )

how can I solve this ? thanks in advance :).

like image 581
yoav.str Avatar asked Feb 01 '26 05:02

yoav.str


2 Answers

I specify my comment into an answer.

You can use this code snippet:

WebMarkupContainer scriptContainer = new WebMarkupContainer("scriptContainer ");
scriptContainer .add(new AttributeAppender("type", Model.of("text/javascript")));
scriptContainer .add(
    new AttributeAppender("src", urlFor(
        new JavaScriptResourceReference(
            YourClass.class, "JavaScriptFile.js"), null).toString()));
add(scriptContainer );

and the corresponding html:

<script wicket:id="scriptContainer "></script>

Just change the string JavaScriptFile.js to load any other Javascript file.

like image 191
rotsch Avatar answered Feb 03 '26 22:02

rotsch


JavascriptPackageResource.getHeaderContributor() does exactly what you need.

You need nothing in your markup, just add the HeaderContributor it returns to your page.

Update: For Wicket 1.5 see the migration guide, but it goes like this:

public class MyPage extends WebPage {
   public MyPage() {
   }
   public void renderHead(IHeaderResponse response) {
     response.renderJavaScriptReference(new PackageResourceReference(YuiLib.class,
       "yahoo-dom-event/yahoo-dom-event.js"));
     response.renderCSSReference(new PackageResourceReference(AbstractCalendar.class,
      "assets/skins/sam/calendar.css"));
   }
}

If you want to put your <script> element in the body, you can simply declare it as a WebMarkupContainer and add an AttributeModifier to set the src attribute. Although in that case wicket won't generate the relative URLs for you, you have to do it yourself.

like image 27
biziclop Avatar answered Feb 03 '26 23:02

biziclop